Compare commits

..
Author SHA1 Message Date
Cursor AgentandTheo Browne d41af12fde Assert smoke runtime imports shared fake codex helper
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 16:07:25 +00:00
Cursor AgentandTheo Browne d01bd5e60a Use shared fake-codex helpers for TS tests and smoke runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 16:04:17 +00:00
Cursor AgentandTheo Browne 9e3e806593 Align CI Bun version with workspace toolchain
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:58:59 +00:00
Cursor AgentandTheo Browne dd947023a5 Guard smoke script fake-codex independence in architecture tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:58:28 +00:00
Cursor AgentandTheo Browne 3e0bdaff2f Bundle runtime-core in t3 build configuration
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:57:17 +00:00
Cursor AgentandTheo Browne eb38f3c475 Share fake codex test helper across runtime test suites
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:49:57 +00:00
Cursor AgentandTheo Browne 8046bd25ca Refresh architecture plan docs for runtime-core ownership
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:47:23 +00:00
Cursor AgentandTheo Browne ef331412b3 Clarify fake-codex test behavior and smoke script usage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:43:24 +00:00
Cursor AgentandTheo Browne 3db534fbac Tighten smoke bootstrap expectations under fake codex runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:41:49 +00:00
Cursor AgentandTheo Browne 54aec2a00f Use fake codex in smoke tests and cover provider happy-path flows
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:39:47 +00:00
Cursor AgentandTheo Browne 796848d2a9 Test bootstrap success path with fake codex runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:34:23 +00:00
Cursor AgentandTheo Browne ef0c62df5d Document runtime-core as sole runtime implementation source
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:22:26 +00:00
Cursor AgentandTheo Browne 30be248837 Add runtime-core provider lifecycle integration test with fake codex
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:20:53 +00:00
Cursor AgentandTheo Browne 0d9f9d1d0f Assert legacy desktop workspace package remains removed
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:17:09 +00:00
Cursor AgentandTheo Browne 2b5fc5297d Cover provider approval-response flow with fake codex app-server
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:16:08 +00:00
Cursor AgentandTheo Browne 350f6bcf85 Add fake codex integration coverage for provider lifecycle RPCs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:12:56 +00:00
Cursor AgentandTheo Browne f2cd81e0c8 Remove desktop compatibility package after runtime-core migration
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:10:22 +00:00
Cursor AgentandTheo Browne 8c74af6c33 Prune obsolete desktop and t3 direct dependencies
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:08:02 +00:00
Cursor AgentandTheo Browne 39fb56b2bc Expand t3 architecture guard to all runtime source files
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:01:29 +00:00
Cursor AgentandTheo Browne 5a963a63e8 Add runtime-core architecture boundary regression tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:00:46 +00:00
Cursor AgentandTheo Browne d6d3e6985b Add desktop compatibility-surface guard tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 15:00:12 +00:00
Cursor AgentandTheo Browne e67d936a37 Update docs for runtime-core codex and provider ownership
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:59:39 +00:00
Cursor AgentandTheo Browne 106f55558e Move codex app-server manager implementation into runtime-core
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:58:25 +00:00
Cursor AgentandTheo Browne 97296d42dd Document provider manager in shared runtime-core package role
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:52:57 +00:00
Cursor AgentandTheo Browne c27785271b Enforce t3 runtime service boundary through runtime-core
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:51:50 +00:00
Cursor AgentandTheo Browne 98d11e156b Route provider manager through shared runtime-core package
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:50:11 +00:00
Cursor AgentandTheo Browne 115367db13 Document runtime-core shared service package in repo guides
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:37:46 +00:00
Cursor AgentandTheo Browne 1bf5a4e389 Add runtime-core tests for process and todo services
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:36:34 +00:00
Cursor AgentandTheo Browne e2cb297b5a Extract process and todo runtime services into shared package
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:34:42 +00:00
Cursor AgentandTheo Browne 669e960ff9 Document shared websocket method registry and coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:17:46 +00:00
Cursor AgentandTheo Browne 9115604af5 Use shared websocket method schema for runtime dispatch
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:16:56 +00:00
Cursor AgentandTheo Browne 2462a90227 Add canonical websocket method list and runtime coverage test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:14:26 +00:00
Cursor AgentandTheo Browne e0a9865d02 Reject empty agent session ids in websocket event envelopes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:04:02 +00:00
Cursor AgentandTheo Browne dd02660502 Require non-empty session ids for agent event payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 14:03:03 +00:00
Cursor AgentandTheo Browne b0113d029e Expand renderer strict nested payload field rejection coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:54:29 +00:00
Cursor AgentandTheo Browne 48fdeab3a1 Document nonblank websocket field requirements
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:44:45 +00:00
Cursor AgentandTheo Browne 2071e98177 Reject blank websocket ids methods and error fields
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:43:54 +00:00
Cursor AgentandTheo Browne 6e3d048d82 Summarize oversized filesystem paths in runtime error messages
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:30:12 +00:00
Cursor AgentandTheo Browne c6d7efc213 Cover renderer handling of overlong websocket error responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:19:54 +00:00
Cursor AgentandTheo Browne a59108c31f Share agent.write input schema across runtime and contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:18:28 +00:00
Cursor AgentandTheo Browne ebd984dd4e Share editor and shell-open input schemas in contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:16:28 +00:00
Cursor AgentandTheo Browne 3b465089a4 Document bounded websocket error envelope semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:14:37 +00:00
Cursor AgentandTheo Browne 170460f6dd Bound websocket error field sizes and sanitize runtime errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:13:58 +00:00
Cursor AgentandTheo Browne 2cf291e504 Document strict core transport contract object semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:02:05 +00:00
Cursor AgentandTheo Browne 2638534226 Make core contract object schemas strict
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 13:01:31 +00:00
Cursor AgentandTheo Browne 2f1eb3d30d Test strict app payload unexpected-field rejection in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:52:36 +00:00
Cursor AgentandTheo Browne a124fd9cb9 Add malformed payload coverage for todo add and provider void RPCs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:50:19 +00:00
Cursor AgentandTheo Browne 6edbcff33c Document over-limit websocket request handling semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:47:59 +00:00
Cursor AgentandTheo Browne 6b2bd27c41 Cover max-length unknown websocket method errors end-to-end
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:47:25 +00:00
Cursor AgentandTheo Browne d8df4dbecb Use shared websocket id bound constant in renderer tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:45:39 +00:00
Cursor AgentandTheo Browne 8afca7081f Make app bootstrap and health result schemas strict
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:44:49 +00:00
Cursor AgentandTheo Browne 5d13d3cd61 Cover max-length websocket request id boundaries end-to-end
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:38:04 +00:00
Cursor AgentandTheo Browne f57cff53e6 Document dialogs and agent coverage in renderer payload validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:30:48 +00:00
Cursor AgentandTheo Browne 0a877b5a7e Share dialogs pick-folder result schema across runtime and renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:30:08 +00:00
Cursor AgentandTheo Browne 00896ff92b Remove redundant renderer event payload re-validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:27:33 +00:00
Cursor AgentandTheo Browne bce4b2a0e5 Document shared runtime and renderer success payload validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:21:29 +00:00
Cursor AgentandTheo Browne f07aed6c97 Use shared app and session schemas in renderer RPC parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:21:00 +00:00
Cursor AgentandTheo Browne e6dcffe027 Resolve contracts imports from source exports in workspace
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:19:37 +00:00
Cursor AgentandTheo Browne 807676a74e Expand app bootstrap and health schema regression tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:12:17 +00:00
Cursor AgentandTheo Browne a8d7b1371b Await async runtime method results before schema validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:10:42 +00:00
Cursor AgentandTheo Browne 65b85a9566 Add renderer malformed-success coverage for spawn turn and shell RPCs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 12:01:52 +00:00
Cursor AgentandTheo Browne 749876208c Expand renderer rejection coverage for malformed RPC success payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:54:18 +00:00
Cursor AgentandTheo Browne 511dcb7bbd Document renderer RPC payload validation safeguards
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:52:32 +00:00
Cursor AgentandTheo Browne 21b1681474 Validate critical renderer RPC payloads before resolving responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:52:08 +00:00
Cursor AgentandTheo Browne 0063db3a20 Document websocket request and method 256-char limits
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:40:31 +00:00
Cursor AgentandTheo Browne e83a163ce8 Test renderer ignores overlong websocket response ids
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:40:15 +00:00
Cursor AgentandTheo Browne c97eccb7a8 Align smoke parser response id bounds with websocket contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:39:48 +00:00
Cursor AgentandTheo Browne ff8341761c Use websocket length constants in runtime malformed-request tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:39:16 +00:00
Cursor AgentandTheo Browne 6ad9bda3c6 Cover overlong websocket request envelopes in runtime and smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:38:52 +00:00
Cursor AgentandTheo Browne 8dd0ec5261 Document websocket request id and method length bounds
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:33:41 +00:00
Cursor AgentandTheo Browne 8d84fdc3f5 Bound websocket request id and method lengths in contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:33:24 +00:00
Cursor AgentandTheo Browne 0ba9932438 Cover strict-invalid websocket envelopes in renderer adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:32:29 +00:00
Cursor AgentandTheo Browne 730e30a6bb Make smoke parser enforce strict websocket top-level keys
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:31:49 +00:00
Cursor AgentandTheo Browne 29b07316e6 Expand strict websocket schema tests for event and error keys
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:31:03 +00:00
Cursor AgentandTheo Browne f28015c47e Ignore malformed extra-field websocket requests safely
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:26:02 +00:00
Cursor AgentandTheo Browne 2642ce3c4b Document strict websocket envelope field handling
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:25:14 +00:00
Cursor AgentandTheo Browne dc4e46ed89 Enforce strict websocket envelope object schemas
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:25:01 +00:00
Cursor AgentandTheo Browne 32e0f58e6d Document typed websocket event payload envelopes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:18:34 +00:00
Cursor AgentandTheo Browne c93cf95cbe Type runtime event fanout by websocket channel contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:18:22 +00:00
Cursor AgentandTheo Browne fcd4bd5a77 Tighten smoke websocket event envelope parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:17:35 +00:00
Cursor AgentandTheo Browne 8313d3c6ca Enforce typed websocket event payload schemas in contracts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:15:51 +00:00
Cursor AgentandTheo Browne 75b853a4dd Assert null agent void RPC results in runtime server tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:08:28 +00:00
Cursor AgentandTheo Browne 12c03c6c98 Document renderer validation of websocket event payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:07:05 +00:00
Cursor AgentandTheo Browne 5bfbe9605c Validate renderer websocket event payload shapes before dispatch
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 11:06:18 +00:00
Cursor AgentandTheo Browne 0d88eaeca0 Validate outbound runtime websocket envelopes before send
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:54:12 +00:00
Cursor AgentandTheo Browne 555f080ae0 Harden smoke websocket parsing with envelope validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:53:26 +00:00
Cursor AgentandTheo Browne a7296d268b Validate runtime websocket test messages against contracts schema
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:50:56 +00:00
Cursor AgentandTheo Browne ffff14edc1 Document stable result field in runtime success responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:50:02 +00:00
Cursor AgentandTheo Browne 2a08d8ea2a Normalize undefined runtime success results to null
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:49:01 +00:00
Cursor AgentandTheo Browne 4b25e84c2e Assert null RPC results for void agent methods in smoke tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:47:13 +00:00
Cursor AgentandTheo Browne 95b1a45d41 Cover over-depth cause-chain fallback in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:41:16 +00:00
Cursor AgentandTheo Browne e4b842b822 Document cause-chain websocket diagnostics extraction
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:33:25 +00:00
Cursor AgentandTheo Browne 634b11d388 Support cause-chain websocket diagnostics extraction in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:33:00 +00:00
Cursor AgentandTheo Browne 44b145e72c Document bounded-depth websocket diagnostics fallback
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:31:01 +00:00
Cursor AgentandTheo Browne 6ea0b0453a Broaden renderer nested error extraction depth coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:30:33 +00:00
Cursor AgentandTheo Browne 1382c944ad Document safe fallback for malformed websocket error payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:29:27 +00:00
Cursor AgentandTheo Browne ec402cfb24 Cover cyclic error payload fallback safety in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:28:14 +00:00
Cursor AgentandTheo Browne 07a775c03f Cover nested and fallback send-failure diagnostics in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:24:21 +00:00
Cursor AgentandTheo Browne 00879b3dcc Support deep nested websocket error payload diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:10:15 +00:00
Cursor AgentandTheo Browne e49b33bbf2 Cover trimmed generic close reason diagnostics in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:05:02 +00:00
Cursor AgentandTheo Browne 37be29136c Cover sliced DataView websocket request payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 10:00:41 +00:00
Cursor AgentandTheo Browne 38f792c737 Cover nested string websocket error payload diagnostics in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:57:21 +00:00
Cursor AgentandTheo Browne 964390d9fb Cover renderer resilience to invalid ws response envelope shapes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:46:51 +00:00
Cursor AgentandTheo Browne 1df8e444e7 Cover dataview and sliced uint8 websocket request payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:43:44 +00:00
Cursor AgentandTheo Browne 95a31b71bd Cover sliced Uint8Array websocket message decoding in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:37:50 +00:00
Cursor AgentandTheo Browne 5b480344fa Tighten websocket response schema result and error invariants
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:35:27 +00:00
Cursor AgentandTheo Browne f16a7c372a Document renderer websocket ArrayBufferView decode support
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:26:08 +00:00
Cursor AgentandTheo Browne dd9cee82d6 Support ArrayBufferView websocket message decoding in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:24:53 +00:00
Cursor AgentandTheo Browne 22c644927f Add websocket contract guards for empty requests and hello version
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:21:59 +00:00
Cursor AgentandTheo Browne 2af6a90fab Expand websocket contract schema validation coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:19:44 +00:00
Cursor AgentandTheo Browne 9d4acd40c3 Cover string send-failure propagation to pending renderer requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:17:20 +00:00
Cursor AgentandTheo Browne 39d0a1f3de Cover non-integer websocket close code normalization in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:15:11 +00:00
Cursor AgentandTheo Browne bf826329fb Document detailed send-failure request diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:12:52 +00:00
Cursor AgentandTheo Browne cbd4ba0f74 Surface non-Error send failure details in renderer requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:12:03 +00:00
Cursor AgentandTheo Browne a4069fb203 Document string websocket error payload diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:03:15 +00:00
Cursor AgentandTheo Browne 8b92651bdf Support string websocket error payload diagnostics in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 09:02:21 +00:00
Cursor AgentandTheo Browne 436a2b89ec Document renderer close metadata normalization
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:51:58 +00:00
Cursor AgentandTheo Browne 539258dd29 Normalize websocket close metadata in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:51:08 +00:00
Cursor AgentandTheo Browne d05ba708e2 Cover no-auth wrong-path unauthorized non-eviction
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:41:11 +00:00
Cursor AgentandTheo Browne 3cab8e6602 Cover wrong-path unauthorized non-eviction behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:38:33 +00:00
Cursor AgentandTheo Browne 90f6d84729 Cover renderer constructor error message normalization edge cases
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:36:05 +00:00
Cursor AgentandTheo Browne 73794df6fa Document constructor failure diagnostics for websocket connect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:32:48 +00:00
Cursor AgentandTheo Browne a5aae62386 Surface websocket constructor failures in renderer connect errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:32:09 +00:00
Cursor AgentandTheo Browne 7298c6cba6 Trim websocket error messages in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:28:54 +00:00
Cursor AgentandTheo Browne 52f9acbf27 Document pending request rejection on websocket send failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:26:14 +00:00
Cursor AgentandTheo Browne c9c70742f1 Reject all pending renderer requests after websocket send failure
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:25:38 +00:00
Cursor AgentandTheo Browne 0705246a51 Document nested websocket error detail reporting
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:16:47 +00:00
Cursor AgentandTheo Browne 1990e7bd26 Surface nested websocket error messages in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:15:05 +00:00
Cursor AgentandTheo Browne 0302f61b88 Guard websocket close metadata uniqueness in contracts tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:11:46 +00:00
Cursor AgentandTheo Browne dfd11e6140 Cover disconnect close code precedence in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:09:18 +00:00
Cursor AgentandTheo Browne 7df0b667f8 Cover pre-open close code precedence in renderer diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:06:56 +00:00
Cursor AgentandTheo Browne ed6f58ae11 Cover no-auth wrong-token-key unauthorized non-eviction
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:04:33 +00:00
Cursor AgentandTheo Browne f048627128 Cover close reason precedence in renderer websocket diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:03:07 +00:00
Cursor AgentandTheo Browne ef5ab36862 Cover wrong-token-key unauthorized non-eviction behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 08:01:41 +00:00
Cursor AgentandTheo Browne be8fccb92d Deduplicate smoke auth token query encoding
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:58:34 +00:00
Cursor AgentandTheo Browne c7e7775bf5 Document lowercase token query key requirement
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:56:34 +00:00
Cursor AgentandTheo Browne 068093c5fb Cover auth token key case-sensitivity websocket rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:56:06 +00:00
Cursor AgentandTheo Browne 706fa19c11 Document renderer websocket reset after send failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:54:28 +00:00
Cursor AgentandTheo Browne fbd55625ed Reset renderer websocket after request send failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:53:56 +00:00
Cursor AgentandTheo Browne 3421e53f96 Cover renderer recovery after transient websocket send failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:51:36 +00:00
Cursor AgentandTheo Browne b1c96a56e6 Cover auth-mode missing-token extra-query websocket rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:49:58 +00:00
Cursor AgentandTheo Browne 995fceaa6c Cover non-eviction for duplicate identical token auth attempts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:48:02 +00:00
Cursor AgentandTheo Browne f831e3b852 Clarify duplicate-token rejection includes identical values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:46:28 +00:00
Cursor AgentandTheo Browne 136570cacc Reject duplicate identical websocket token parameters
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:45:56 +00:00
Cursor AgentandTheo Browne 10bb74b81e Clarify stale provider and agent stream isolation docs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:44:11 +00:00
Cursor AgentandTheo Browne 817541ca52 Cover stale agent event isolation after renderer reconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:42:45 +00:00
Cursor AgentandTheo Browne ebfd4057ce Cover stale provider event isolation after renderer reconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:40:58 +00:00
Cursor AgentandTheo Browne bb9804cf70 Cover stale websocket message isolation after renderer reconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:38:23 +00:00
Cursor AgentandTheo Browne 5323a138c4 Document renderer auto-reconnect after close and error disconnects
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:36:23 +00:00
Cursor AgentandTheo Browne b2d7c3e242 Cover renderer reconnect after idle websocket error
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:35:38 +00:00
Cursor AgentandTheo Browne 4a5c2bf711 Cover concurrent pending request rejection on websocket error
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:33:52 +00:00
Cursor AgentandTheo Browne 124cd5ea0d Cover renderer stale-error isolation and generic error fallback
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:32:54 +00:00
Cursor AgentandTheo Browne 9598488fe9 Document renderer websocket connect error detail reporting
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:25:43 +00:00
Cursor AgentandTheo Browne 091f9f2a69 Report websocket open error details in renderer connect failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:25:04 +00:00
Cursor AgentandTheo Browne 166e11c1a9 Document stale websocket event isolation after reconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:19:01 +00:00
Cursor AgentandTheo Browne f3a5077010 Ignore stale websocket events after renderer reconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:18:25 +00:00
Cursor AgentandTheo Browne dc60bdb1bc Document renderer websocket error-event request failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:12:31 +00:00
Cursor AgentandTheo Browne 73f2b3e4ae Handle websocket error events for pending renderer requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:11:56 +00:00
Cursor AgentandTheo Browne 7c423d46b7 Cover concurrent pending request rejection on unauthorized disconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:06:24 +00:00
Cursor AgentandTheo Browne 5b81ceb0e1 Cover renderer reconnect after unauthorized pending-request disconnect
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:01:20 +00:00
Cursor AgentandTheo Browne 0fb1da8371 Cover renderer reconnection after unauthorized and replacement closes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 07:00:36 +00:00
Cursor AgentandTheo Browne 4633e3f0a3 Cover renderer reason-only close metadata mappings
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:55:32 +00:00
Cursor AgentandTheo Browne 30c19f0e71 Surface reason-only websocket close diagnostics in renderer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:54:44 +00:00
Cursor AgentandTheo Browne 273ac4bbb8 Cover renderer close code-only fallback messaging
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:49:40 +00:00
Cursor AgentandTheo Browne c183380225 Cover renderer websocket close-metadata fallback branches
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:48:57 +00:00
Cursor AgentandTheo Browne 9cef7b77d5 Document renderer in-flight disconnect diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:43:48 +00:00
Cursor AgentandTheo Browne 324b94381f Improve renderer request disconnect errors with close metadata
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:43:18 +00:00
Cursor AgentandTheo Browne beb26880eb Document renderer websocket close-metadata diagnostics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:42:32 +00:00
Cursor AgentandTheo Browne 43173d100c Expand renderer websocket close metadata test coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:42:03 +00:00
Cursor AgentandTheo Browne d5f970c961 Surface websocket close metadata in renderer connection errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:36:34 +00:00
Cursor AgentandTheo Browne 4966661956 Test shared websocket close metadata constants
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:29:23 +00:00
Cursor AgentandTheo Browne f7ae3e85ea Centralize websocket close constants in smoke harness
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:28:40 +00:00
Cursor AgentandTheo Browne d9b539a661 Use shared websocket close constants in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:27:54 +00:00
Cursor AgentandTheo Browne 3cbec3a139 Introduce shared websocket close code and reason constants
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:27:11 +00:00
Cursor AgentandTheo Browne 7e2bbaa403 Assert unauthorized close reasons in non-eviction scenarios
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:20:45 +00:00
Cursor AgentandTheo Browne 775c5d797a Assert unauthorized close reasons across auth token rejection cases
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:19:34 +00:00
Cursor AgentandTheo Browne 27269388aa Assert unauthorized close reasons in no-auth websocket rejections
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:18:49 +00:00
Cursor AgentandTheo Browne 30cfb90254 Cover buffer websocket request payloads in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:18:17 +00:00
Cursor AgentandTheo Browne c30a9e3152 Assert websocket close reasons in smoke authorization checks
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:13:22 +00:00
Cursor AgentandTheo Browne cd2da30eb4 Document unauthorized websocket close semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:12:20 +00:00
Cursor AgentandTheo Browne 503e6d8a75 Assert unauthorized websocket close reason semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:11:56 +00:00
Cursor AgentandTheo Browne dda8abba23 Document websocket replacement close reason
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:11:26 +00:00
Cursor AgentandTheo Browne d8b62998da Cover arraybuffer smoke requests and replacement close reasons
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:11:06 +00:00
Cursor AgentandTheo Browne 992532873c Harden smoke websocket helpers for close/error handling
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:05:49 +00:00
Cursor AgentandTheo Browne f997cc3716 Assert listSessions reflects bootstrap session when startup succeeds
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:05:09 +00:00
Cursor AgentandTheo Browne c4b7956430 Assert malformed websocket tolerance and unknown agent controls
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 06:03:55 +00:00
Cursor AgentandTheo Browne 4cb1055551 Document websocket replacement close code semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:59:13 +00:00
Cursor AgentandTheo Browne 92ca009560 Cover no-auth token-query websocket rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:58:30 +00:00
Cursor AgentandTheo Browne b6b20455e4 Cover binary websocket request payloads in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:58:03 +00:00
Cursor AgentandTheo Browne 397edfe088 Assert terminal.run timeout semantics in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:57:27 +00:00
Cursor AgentandTheo Browne 1488f40bae Cover invalid todos and shell cwd payload errors in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:56:52 +00:00
Cursor AgentandTheo Browne 8da9a329a3 Assert invalid providers payload errors in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:54:31 +00:00
Cursor AgentandTheo Browne 64152e816d Exercise agent.kill and agent.write RPCs in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:47:39 +00:00
Cursor AgentandTheo Browne 684388fbbf Cover no-auth unexpected-query unauthorized non-eviction
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:46:24 +00:00
Cursor AgentandTheo Browne 90da976395 Assert structured validation errors in websocket smoke flow
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:45:50 +00:00
Cursor AgentandTheo Browne 90ec32f69c Cover providers.listSessions RPC in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:44:55 +00:00
Cursor AgentandTheo Browne fae88186f9 Exercise agent event streaming over websocket in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:44:28 +00:00
Cursor AgentandTheo Browne 0d6e84fe81 Cover extra-query unauthorized connection non-eviction
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:39:41 +00:00
Cursor AgentandTheo Browne 6098003dad Require strict websocket query params for authorization
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:38:23 +00:00
Cursor AgentandTheo Browne 8e88da9add Assert app.bootstrap payload contract in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:35:50 +00:00
Cursor AgentandTheo Browne 6606bd4b60 Validate terminal.run RPC success in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:35:22 +00:00
Cursor AgentandTheo Browne ec7eb7bc56 Exercise todos websocket CRUD flow in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:34:44 +00:00
Cursor AgentandTheo Browne 825a48e1cc Verify active-client replacement behavior in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:33:35 +00:00
Cursor AgentandTheo Browne 1b65041ac3 Document root-path websocket connection requirement
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:28:23 +00:00
Cursor AgentandTheo Browne 76be201215 Reject websocket connections on non-root paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:28:10 +00:00
Cursor AgentandTheo Browne 144143544a Verify structured unknown-method websocket errors in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:26:49 +00:00
Cursor AgentandTheo Browne d68b1bbc68 Assert conditional 304 content-type header stability
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:20:37 +00:00
Cursor AgentandTheo Browne a83aec31ca Cover malformed whitespace-only suffix range rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:19:23 +00:00
Cursor AgentandTheo Browne 0c69ed5452 Cover mixed-case spaced suffix range parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:18:12 +00:00
Cursor AgentandTheo Browne 7c070b6425 Assert duplicate-token auth attempts do not evict active client
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:17:09 +00:00
Cursor AgentandTheo Browne 8edbf85b54 Cover duplicate-token unauthorized non-eviction behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:15:25 +00:00
Cursor AgentandTheo Browne e6b40ac013 Document duplicate-token websocket auth rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:14:22 +00:00
Cursor AgentandTheo Browne 7f29e39d9d Reject duplicate websocket token parameters
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:12:56 +00:00
Cursor AgentandTheo Browne cd327137fd Cover whitespace-padded suffix and open-ended ranges
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:07:15 +00:00
Cursor AgentandTheo Browne c1bec99a7a Cover unknown T3_NO_OPEN value handling
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:02:11 +00:00
Cursor AgentandTheo Browne aa016aa047 Assert whitespace websocket token rejection in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 05:00:32 +00:00
Cursor AgentandTheo Browne 8951ec7072 Cover whitespace token query rejection for auth runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:59:32 +00:00
Cursor AgentandTheo Browne b16ca1c9ee Cover falsey T3_NO_OPEN environment parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:58:36 +00:00
Cursor AgentandTheo Browne 0e775333a0 Document full T3_NO_OPEN boolean token support
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:57:40 +00:00
Cursor AgentandTheo Browne 8364f8a166 Cover trimmed uppercase T3_NO_OPEN falsey parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:56:11 +00:00
Cursor AgentandTheo Browne 4627c42841 Cover trimmed uppercase T3_NO_OPEN truthy parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:55:18 +00:00
Cursor AgentandTheo Browne fa4089f461 Cover tabbed environment port trimming semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:54:26 +00:00
Cursor AgentandTheo Browne 288c773b3e Assert empty websocket token rejection in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:52:56 +00:00
Cursor AgentandTheo Browne a1021ecd49 Cover empty token query rejection for auth runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:52:00 +00:00
Cursor AgentandTheo Browne 2a88b31f3a Assert tab-spaced Range headers in smoke coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:50:32 +00:00
Cursor AgentandTheo Browne 1929660b3b Cover tab-separated Range header whitespace tolerance
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:49:40 +00:00
Cursor AgentandTheo Browne de10ddea16 Cover zero environment backend and web port rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:48:13 +00:00
Cursor AgentandTheo Browne c557259673 Cover zero explicit backend and web port rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:47:18 +00:00
Cursor AgentandTheo Browne c9b921c532 Clarify valid CLI port value range in docs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:45:48 +00:00
Cursor AgentandTheo Browne eef8485eb4 Cover null runtime port startup rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:44:50 +00:00
Cursor AgentandTheo Browne 933cc42054 Assert ranged If-Unmodified-Since and If-None-Match behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:44:00 +00:00
Cursor AgentandTheo Browne 78eea79845 Assert current If-Unmodified-Since with If-None-Match
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:42:56 +00:00
Cursor AgentandTheo Browne 741c02eaba Refactor first-header extraction across conditional helpers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:42:02 +00:00
Cursor AgentandTheo Browne 0d7afe0021 Document oversized suffix range normalization behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:40:47 +00:00
Cursor AgentandTheo Browne 3180b28b33 Assert oversized suffix range fallback in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:40:02 +00:00
Cursor AgentandTheo Browne 8a424f2c03 Cover oversized suffix range clamping semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:39:12 +00:00
Cursor AgentandTheo Browne fb6a083b5b Cover null launchCwd startup rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:38:23 +00:00
Cursor AgentandTheo Browne d90ec00087 Assert stale ranged If-Modified-Since returns partial content
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:37:36 +00:00
Cursor AgentandTheo Browne 738a1de007 Assert mismatched If-None-Match keeps ranged 206 flow
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:36:43 +00:00
Cursor AgentandTheo Browne 482aeb7c57 Cover trimmed comma-separated If-Match tokens
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:35:48 +00:00
Cursor AgentandTheo Browne b520aa63f4 Cover null runtime auth token startup rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:35:06 +00:00
Cursor AgentandTheo Browne 6b20a47021 Assert HEAD wildcard If-Match and If-None-Match behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:34:22 +00:00
Cursor AgentandTheo Browne 965a21f973 Cover wildcard If-Match support in array headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:33:35 +00:00
Cursor AgentandTheo Browne 3eb0abbc53 Clarify non-empty cwd requirement in docs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:32:47 +00:00
Cursor AgentandTheo Browne 198621a881 Cover whitespace-only launchCwd startup rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:32:06 +00:00
Cursor AgentandTheo Browne 1acc3a5141 Cover non-number runtime option rejection paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:31:24 +00:00
Cursor AgentandTheo Browne b0482d89f4 Document tolerant whitespace in Range header parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:30:30 +00:00
Cursor AgentandTheo Browne 94e661f01d Assert spaced Range headers in smoke coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:29:50 +00:00
Cursor AgentandTheo Browne aa455d13cc Allow optional spaces in Range header parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:29:07 +00:00
Cursor AgentandTheo Browne 0431e648c8 Assert wildcard If-Match with If-None-Match interplay
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:24:34 +00:00
Cursor AgentandTheo Browne 8e1db9f909 Assert wildcard If-None-Match with range returns 304
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:23:16 +00:00
Cursor AgentandTheo Browne 7d17ff43fd Cover invalid-first If-Unmodified-Since array semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:22:31 +00:00
Cursor AgentandTheo Browne 347474a6b2 Cover If-Modified-Since array first-value precedence
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:21:51 +00:00
Cursor AgentandTheo Browne 60e6d7a2e8 Cover trimmed case-insensitive short -o values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:21:10 +00:00
Cursor AgentandTheo Browne df14dafe32 Document If-Unmodified-Since precedence over 304 paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:20:31 +00:00
Cursor AgentandTheo Browne 396d1c311b Assert If-Unmodified-Since failures override If-None-Match
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:19:57 +00:00
Cursor AgentandTheo Browne 2b33d2881c Document If-Match precedence over cache validators
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:19:12 +00:00
Cursor AgentandTheo Browne fea6876a46 Assert If-Match precedence over If-None-Match mismatches
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:18:33 +00:00
Cursor AgentandTheo Browne 926d1a03a9 Assert If-Match and If-None-Match combined behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:17:54 +00:00
Cursor AgentandTheo Browne 3155e47d99 Assert HEAD stale If-Unmodified-Since validator headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:17:08 +00:00
Cursor AgentandTheo Browne 587cca9b84 Cover If-Unmodified-Since array first-value precedence
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:16:28 +00:00
Cursor AgentandTheo Browne 95b52ecb47 Assert wildcard If-Match preserves ranged responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:15:48 +00:00
Cursor AgentandTheo Browne b36185d40e Cover whitespace-trimmed weak If-None-Match parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:14:38 +00:00
Cursor AgentandTheo Browne 5493a814b7 Document strong versus weak static validator semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:14:02 +00:00
Cursor AgentandTheo Browne ab400664bd Expand ETag precondition helper edge-case tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:13:24 +00:00
Cursor AgentandTheo Browne e33e0e42dd Cover client socket shutdown on runtime close
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:12:40 +00:00
Cursor AgentandTheo Browne a735874acf Extract static precondition-failure response helper
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:11:39 +00:00
Cursor AgentandTheo Browne 9ebf691747 Assert 412 responses keep range capability headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:10:49 +00:00
Cursor AgentandTheo Browne 262f9e242c Assert lowercase weak validator behavior in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:09:44 +00:00
Cursor AgentandTheo Browne 28ee12ba15 Handle lowercase weak ETag validators consistently
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:08:59 +00:00
Cursor AgentandTheo Browne 028a1786f7 Cover If-Range array-first-value semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:08:01 +00:00
Cursor AgentandTheo Browne fd1fbe45a7 Assert invalid If-Range dates fall back to full response
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:07:18 +00:00
Cursor AgentandTheo Browne 912901c3b6 Document wildcard static validator support
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:06:20 +00:00
Cursor AgentandTheo Browne f6f9900104 Refactor static validator and range header emission
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:05:27 +00:00
Cursor AgentandTheo Browne e92d432cae Expand short -o equals-value parser coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:04:08 +00:00
Cursor AgentandTheo Browne a80816d86c Cover comma-separated If-Match value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:03:04 +00:00
Cursor AgentandTheo Browne ae24ea691c Assert HEAD stale If-Unmodified-Since failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:02:09 +00:00
Cursor AgentandTheo Browne 0aebf5b590 Document 416 static range validator metadata
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:01:12 +00:00
Cursor AgentandTheo Browne 8b93f3b144 Include validators on 416 static range responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 04:00:21 +00:00
Cursor AgentandTheo Browne 9dffec959c Cover byte-range parsing invalid file-size inputs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:54:47 +00:00
Cursor AgentandTheo Browne 390c340bdc Cover auth token trimming across whitespace characters
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:53:55 +00:00
Cursor AgentandTheo Browne c41fe91c51 Cover bootstrap timeout lower bound acceptance
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:53:06 +00:00
Cursor AgentandTheo Browne 30dcbb3877 Cover If-Range wildcard rejection semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:52:13 +00:00
Cursor AgentandTheo Browne 82ee14bc7e Assert wildcard If-None-Match and If-Match behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:51:19 +00:00
Cursor AgentandTheo Browne 44728d6cd3 Expand If-Match and If-Unmodified-Since helper tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:50:27 +00:00
Cursor AgentandTheo Browne d4b999650f Assert 412 precondition content-type and length headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:48:52 +00:00
Cursor AgentandTheo Browne 9ebee1113d Document 412 static validator response headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:47:53 +00:00
Cursor AgentandTheo Browne c5b1cd7c94 Include validators on 412 static precondition responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:47:07 +00:00
Cursor AgentandTheo Browne ec2012e0d2 Assert ranged If-Unmodified-Since precondition failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:45:49 +00:00
Cursor AgentandTheo Browne fae9aeba8d Assert range requests honor If-Match preconditions
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:44:59 +00:00
Cursor AgentandTheo Browne 262d5088f8 Assert If-Match precedence over If-Unmodified-Since
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:44:05 +00:00
Cursor AgentandTheo Browne ffa2756cf6 Assert 412 precondition responses keep no-store policy
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:43:14 +00:00
Cursor AgentandTheo Browne b80e1dcac2 Document If-Match and If-Unmodified-Since support
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:42:24 +00:00
Cursor AgentandTheo Browne 8aa5ed80f5 Support If-Match and If-Unmodified-Since preconditions
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:41:39 +00:00
Cursor AgentandTheo Browne 3e109a88e6 Document Last-Modified static validator headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:35:55 +00:00
Cursor AgentandTheo Browne 2ba14edf36 Assert Last-Modified stability on conditional responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:35:12 +00:00
Cursor AgentandTheo Browne d81c547169 Assert HEAD asset ETag and Last-Modified headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:34:23 +00:00
Cursor AgentandTheo Browne 44604dd0c6 Document whitespace cwd rejection for runtime APIs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:33:04 +00:00
Cursor AgentandTheo Browne 33edb9235d Reject whitespace cwd values for runtime path APIs
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:32:13 +00:00
Cursor AgentandTheo Browne dcb44cb729 Reject empty launchCwd values at runtime startup
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:30:05 +00:00
Cursor AgentandTheo Browne 60e9c8c00b Assert stale If-Range date falls back to full response
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:29:01 +00:00
Cursor AgentandTheo Browne e0b1b7a44d Validate runtime auth token type at startup
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:27:43 +00:00
Cursor AgentandTheo Browne 665b435ca4 Cover byte-range whitespace and multi-range parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:26:02 +00:00
Cursor AgentandTheo Browne e1f6c86c75 Cover NaN and infinite bootstrap timeout rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:25:21 +00:00
Cursor AgentandTheo Browne 79de5bf9a2 Assert weak If-Range falls back to full response
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:23:57 +00:00
Cursor AgentandTheo Browne d941966436 Document conditional precondition precedence over ranges
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:23:12 +00:00
Cursor AgentandTheo Browne 28db4bb777 Apply conditional preconditions before range handling
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:22:28 +00:00
Cursor AgentandTheo Browne 8f2fd0919c Assert 304 static responses preserve security headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:19:53 +00:00
Cursor AgentandTheo Browne 56bb28267d Expand If-Range helper edge-case coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:18:47 +00:00
Cursor AgentandTheo Browne 13d771a71f Assert ranged If-Modified-Since remains partial
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:18:10 +00:00
Cursor AgentandTheo Browne 035d257d98 Document static If-Range response semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:17:20 +00:00
Cursor AgentandTheo Browne f358ab2a3c Honor If-Range semantics for static byte requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:16:41 +00:00
Cursor AgentandTheo Browne 830dd2e118 Document If-Modified-Since static caching behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:15:04 +00:00
Cursor AgentandTheo Browne f8aae93a16 Add Last-Modified conditional handling for static files
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:14:28 +00:00
Cursor AgentandTheo Browne 4ed9832794 Assert 304 responses omit content-length in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:12:38 +00:00
Cursor AgentandTheo Browne adac335c3f Support weak If-None-Match ETag comparison
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:11:52 +00:00
Cursor AgentandTheo Browne 55faded027 Cover conditional HEAD static responses in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:10:45 +00:00
Cursor AgentandTheo Browne 1934d79dba Document static ETag and conditional cache behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:10:03 +00:00
Cursor AgentandTheo Browne f6210af9d0 Add ETag conditional handling for static files
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:09:07 +00:00
Cursor AgentandTheo Browne 01b32b2d35 Expose range capability headers on 416 responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 03:04:27 +00:00
Cursor AgentandTheo Browne 6ae469074c Refactor static file GET and HEAD response path
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:59:48 +00:00
Cursor AgentandTheo Browne d315271987 Document static Vary range header behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:58:18 +00:00
Cursor AgentandTheo Browne 133a9cd5a9 Add Vary header for static range responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:57:50 +00:00
Cursor AgentandTheo Browne 10c7207895 Cover zero-length file byte-range rejection cases
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:56:57 +00:00
Cursor AgentandTheo Browne cf73b44095 Cover case-insensitive byte range unit parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:56:27 +00:00
Cursor AgentandTheo Browne b03573eeb0 Cover HEAD unsatisfiable range responses in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:55:43 +00:00
Cursor AgentandTheo Browne d168f0ea0d Assert HEAD byte-range behavior in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:55:08 +00:00
Cursor AgentandTheo Browne 3f5c18850d Document static byte-range response support
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:54:34 +00:00
Cursor AgentandTheo Browne 50cfbd4393 Add byte-range support to static asset responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:54:05 +00:00
Cursor AgentandTheo Browne 28ac180980 Use direct runtime manager imports in API server
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:50:41 +00:00
Cursor AgentandTheo Browne e1ba3988a1 Document static range and security response headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:49:15 +00:00
Cursor AgentandTheo Browne fd72e0ae3f Serve and assert Accept-Ranges on static files
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:48:44 +00:00
Cursor AgentandTheo Browne a020b53e44 Cover bootstrap timeout upper bound acceptance
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:47:27 +00:00
Cursor AgentandTheo Browne 9b8d67e932 Handle uppercase absolute request URL schemes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:43:55 +00:00
Cursor AgentandTheo Browne 814f075ddc Cover -o=true override of T3_NO_OPEN env
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:42:43 +00:00
Cursor AgentandTheo Browne cbb0476d29 Cover --web-port guard for -o=bool token
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:41:41 +00:00
Cursor AgentandTheo Browne 5e8665bb13 Exercise -o=0 launch path in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:40:41 +00:00
Cursor AgentandTheo Browne 3c222b17b7 Support equals-style short -o boolean parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:39:42 +00:00
Cursor AgentandTheo Browne ffe58dbb90 Cover -o token guards after value-taking flags
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:38:00 +00:00
Cursor AgentandTheo Browne 6509eefec2 Add -o short alias for open flag
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:37:05 +00:00
Cursor AgentandTheo Browne d95e2fc125 Cover empty equals-style --open parsing errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:35:33 +00:00
Cursor AgentandTheo Browne f96ecb6d06 Use --open=0 path in smoke launch arguments
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:34:40 +00:00
Cursor AgentandTheo Browne ce06a538c6 Cover numeric equals-style --open parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:33:43 +00:00
Cursor AgentandTheo Browne c31f0c8de2 Assert HEAD missing-asset content-length in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:32:49 +00:00
Cursor AgentandTheo Browne 4fb9e1769c Assert HEAD asset content-length in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:31:57 +00:00
Cursor AgentandTheo Browne e8dee9f7b6 Cover --open token as missing port argument value
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:31:01 +00:00
Cursor AgentandTheo Browne 845ab9a76b Destroy static file stream when response closes
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:30:05 +00:00
Cursor AgentandTheo Browne f5b1b638ce Stream static file responses instead of buffering
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:29:11 +00:00
Cursor AgentandTheo Browne 524c11709a Cover end-marker use after positional cwd selection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:24:53 +00:00
Cursor AgentandTheo Browne d47b08fc99 Cover T3_NO_OPEN false-value environment parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:23:47 +00:00
Cursor AgentandTheo Browne 1870118593 Cover equals-style open/no-open precedence rules
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:22:55 +00:00
Cursor AgentandTheo Browne 9da397664f Assert HEAD asset security headers in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:22:03 +00:00
Cursor AgentandTheo Browne 98d09fa267 Assert HEAD missing-asset security headers in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:21:09 +00:00
Cursor AgentandTheo Browne 81a80e7f06 Expand unknown argument parser coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:20:15 +00:00
Cursor AgentandTheo Browne 48d5f7263c Cover absolute-form resolution in static read-target helper
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:19:23 +00:00
Cursor AgentandTheo Browne cab673a105 Cover NaN and infinite runtime port rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:18:33 +00:00
Cursor AgentandTheo Browne 2d7754c19f Handle absolute-form static request targets safely
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:17:34 +00:00
Cursor AgentandTheo Browne 1345ec325a Assert HEAD security headers in smoke checks
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:14:13 +00:00
Cursor AgentandTheo Browne ed3d0be205 Cover --open token guards for port value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:12:43 +00:00
Cursor AgentandTheo Browne 2c885142b2 Cover trimmed equals-style --open parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:09:24 +00:00
Cursor AgentandTheo Browne 20ac731149 Assert HEAD missing-asset cache behavior in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:08:12 +00:00
Cursor AgentandTheo Browne 148711b2ac Assert missing-asset security headers in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:07:16 +00:00
Cursor AgentandTheo Browne e58bc32113 Trim whitespace in explicit CLI port values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:06:22 +00:00
Cursor AgentandTheo Browne bc65ad73aa Assert built asset frame and referrer headers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:04:40 +00:00
Cursor AgentandTheo Browne ab9e47fae4 Document accepted boolean values for --open
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:03:49 +00:00
Cursor AgentandTheo Browne 35e381dcbf Cover --open=off equals-value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:03:10 +00:00
Cursor AgentandTheo Browne 5bb68e21b5 Exercise --open=false path in smoke launch
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:02:29 +00:00
Cursor AgentandTheo Browne 7a704b2eae Treat equals-style flags as missing arg values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:01:40 +00:00
Cursor AgentandTheo Browne 86e541a697 Cover --open=true equals-value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 02:00:07 +00:00
Cursor AgentandTheo Browne 9be9837d48 Support equals-style boolean values for --open
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:59:28 +00:00
Cursor AgentandTheo Browne e61ed3ce38 Cover --cwd missing-value guard for --open token
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:58:21 +00:00
Cursor AgentandTheo Browne ed8e29dedc Add --open flag to override no-open defaults
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:57:39 +00:00
Cursor AgentandTheo Browne e0089ea5c7 Cover query-plus-fragment static path parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:53:56 +00:00
Cursor AgentandTheo Browne 01021f85df Refactor CLI boolean token parsing constants
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:53:11 +00:00
Cursor AgentandTheo Browne 3f59add5b4 Cover T3_NO_OPEN off-value environment parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:52:23 +00:00
Cursor AgentandTheo Browne bb152c985c Cover --no-open=yes equals-value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:51:39 +00:00
Cursor AgentandTheo Browne adb7824166 Cover off-value handling for --no-open
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:50:36 +00:00
Cursor AgentandTheo Browne 6ce75a0b3a Cover trimmed equals-style --no-open parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:49:51 +00:00
Cursor AgentandTheo Browne 2fbf261d52 Assert built asset COOP header in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:49:15 +00:00
Cursor AgentandTheo Browne b6eeef55bc Add COOP headers to static runtime responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:48:35 +00:00
Cursor AgentandTheo Browne 3397175977 Expand --no-open equals-value parser coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:47:31 +00:00
Cursor AgentandTheo Browne d943f75b7c Support equals-style boolean values for --no-open
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:46:49 +00:00
Cursor AgentandTheo Browne 2c3789dd40 Assert HEAD asset cache headers in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:45:31 +00:00
Cursor AgentandTheo Browne 1db2ef8e82 Assert built asset security headers in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:44:49 +00:00
Cursor AgentandTheo Browne 9b3ffaa235 Strip URL hash fragments in static path resolution
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:43:59 +00:00
Cursor AgentandTheo Browne 4e3b3d0a80 Refactor static security header assignment
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:42:59 +00:00
Cursor AgentandTheo Browne b800536e74 Assert POST error content-length in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:41:40 +00:00
Cursor AgentandTheo Browne ebf290e8f5 Assert POST error content-type in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:41:03 +00:00
Cursor AgentandTheo Browne 5b28cfbbe9 Reset active client reference during runtime shutdown
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:40:18 +00:00
Cursor AgentandTheo Browne ea0f27dc60 Clear active client pointer on socket error closure
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:39:35 +00:00
Cursor AgentandTheo Browne d3f580dc95 Cover end-marker handling after flag value parsers
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:38:53 +00:00
Cursor AgentandTheo Browne 79028d6952 Add X-Frame-Options to static runtime responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:38:09 +00:00
Cursor AgentandTheo Browne d161e0b987 Cover validateLaunchDirectory relative cwd resolution
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:37:20 +00:00
Cursor AgentandTheo Browne 4915ff769a Cover CLI version fallback for blank env value
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:36:29 +00:00
Cursor AgentandTheo Browne 2752dbbd02 Add CORP headers to static runtime responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:35:49 +00:00
Cursor AgentandTheo Browne 3ac9d76509 Cover relative missing terminal cwd error details
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:35:01 +00:00
Cursor AgentandTheo Browne 516b86c825 Cover relative missing shell target error details
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:34:27 +00:00
Cursor AgentandTheo Browne 282ff394dd Cover plus-prefixed port rejection cases
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:33:51 +00:00
Cursor AgentandTheo Browne 6cb05e1c0e Document static cache-control behavior in README
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:33:19 +00:00
Cursor AgentandTheo Browne 59f56ce3a8 Add referrer-policy headers to static responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:32:23 +00:00
Cursor AgentandTheo Browne dbff0f96d3 Assert static asset max-age cache policy in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:31:38 +00:00
Cursor AgentandTheo Browne 0a1a0c0a27 Require decimal-only CLI port values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:30:53 +00:00
Cursor AgentandTheo Browne 5badab515f Preserve original causes in directory access errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:30:04 +00:00
Cursor AgentandTheo Browne 976ff6fcdf Assert HEAD cache-control semantics in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:28:41 +00:00
Cursor AgentandTheo Browne 5f17ee8a33 Expand end-of-options positional parsing coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:28:02 +00:00
Cursor AgentandTheo Browne e060cf4fd4 Assert POST error response security headers in smoke
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:27:25 +00:00
Cursor AgentandTheo Browne 855923ce13 Bound bootstrap timeout configuration range
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:26:51 +00:00
Cursor AgentandTheo Browne f951587e52 Cover port flags rejecting known-flag values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:26:01 +00:00
Cursor AgentandTheo Browne 8f9096c626 Parse negative port args as invalid values
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:25:31 +00:00
Cursor AgentandTheo Browne ea69ec16fe Cover equals-style dash-prefixed cwd parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:23:01 +00:00
Cursor AgentandTheo Browne 271d78a9a5 Set immutable cache headers for built static assets
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:22:29 +00:00
Cursor AgentandTheo Browne 7957e29cbf Mark static error responses as no-store
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:19:35 +00:00
Cursor AgentandTheo Browne a04f832761 Cover trimmed environment port parsing semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:18:43 +00:00
Cursor AgentandTheo Browne a0ef9976df Apply nosniff headers to static error responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:18:03 +00:00
Cursor AgentandTheo Browne bb00a48f70 Document launch-based relative cwd resolution
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:17:14 +00:00
Cursor AgentandTheo Browne 77ebbad521 Resolve relative runtime cwd paths from launch directory
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:16:41 +00:00
Cursor AgentandTheo Browne b2263e752f Cover safe in-dist symlink static resolution
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:14:56 +00:00
Cursor AgentandTheo Browne fc16b8ac58 Disable HTML caching in static runtime responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:14:17 +00:00
Cursor AgentandTheo Browne 524ba15e62 Document runtime cwd defaults and validation behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:13:25 +00:00
Cursor AgentandTheo Browne 8a1ad4e763 Reuse shared directory validation in runtime methods
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:12:50 +00:00
Cursor AgentandTheo Browne eed51b69d9 Cover non-integer runtime port startup rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:12:02 +00:00
Cursor AgentandTheo Browne c0becc4431 Validate runtime server port range on startup
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:11:29 +00:00
Cursor AgentandTheo Browne 5326137670 Validate bootstrap timeout configuration at startup
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:10:21 +00:00
Cursor AgentandTheo Browne a201790c40 Default terminal.run cwd to launch project directory
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:09:35 +00:00
Cursor AgentandTheo Browne c217a55d3d Assert static POST rejection in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:08:38 +00:00
Cursor AgentandTheo Browne 94b265759b Allow dash-prefixed cwd values in --cwd form
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:08:03 +00:00
Cursor AgentandTheo Browne 79f54596e7 Document launch directory validation requirement
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:05:13 +00:00
Cursor AgentandTheo Browne b0d168b6ae Validate runtime launchCwd before server startup
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:04:52 +00:00
Cursor AgentandTheo Browne 053488cd66 Cover relative shell editor cwd handling
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:04:06 +00:00
Cursor AgentandTheo Browne bf2d01729f Cover relative cwd resolution in terminal integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:03:32 +00:00
Cursor AgentandTheo Browne b54a6bc127 Validate shell editor targets are directories
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:03:02 +00:00
Cursor AgentandTheo Browne a9ef944b9d Assert missing static assets return 404 in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:01:58 +00:00
Cursor AgentandTheo Browne 525c0f6a34 Return 404 for missing static assets with extensions
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:01:23 +00:00
Cursor AgentandTheo Browne 9f3f723db8 Trim CLI version sources before reporting
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 01:00:38 +00:00
Cursor AgentandTheo Browne d013808e3f Handle oversized websocket payload errors safely
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:59:45 +00:00
Cursor AgentandTheo Browne 9a5a8c7e5d Cap websocket client payload size in runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:58:51 +00:00
Cursor AgentandTheo Browne 62bdc914e8 Cover terminal cwd file-path validation error
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:58:13 +00:00
Cursor AgentandTheo Browne e018d55032 Validate terminal cwd exists before command execution
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:57:43 +00:00
Cursor AgentandTheo Browne ead26b4c26 Optimize static HEAD responses with content-length
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:56:32 +00:00
Cursor AgentandTheo Browne 678da637a6 Support HEAD and 405 handling in static server
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:55:40 +00:00
Cursor AgentandTheo Browne 31733ba5c0 Add nosniff header for static runtime responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:54:51 +00:00
Cursor AgentandTheo Browne 9bc6b6529a Document end-of-options path flag usage
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:53:53 +00:00
Cursor AgentandTheo Browne be21363654 Support -- end-of-options path parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:53:19 +00:00
Cursor AgentandTheo Browne a5b9eb61c9 Validate launch directory before starting runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:52:40 +00:00
Cursor AgentandTheo Browne a9bb1d6b19 Reject null-byte encoded static asset paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:50:26 +00:00
Cursor AgentandTheo Browne 06785908e1 Return 404 when static fallback index is missing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:49:52 +00:00
Cursor AgentandTheo Browne 92bedca342 Assert unauthorized sockets receive no frames in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:49:14 +00:00
Cursor AgentandTheo Browne fcc8117975 Cache static dist realpath across requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:48:34 +00:00
Cursor AgentandTheo Browne 8dd83d1f5c Reject empty env port values in CLI parser
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:48:00 +00:00
Cursor AgentandTheo Browne f86860cff2 Cover backend env port upper-bound validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:46:01 +00:00
Cursor AgentandTheo Browne be9c7df998 Block static server symlink escape paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:45:20 +00:00
Cursor AgentandTheo Browne e0d34cd373 Validate CLI ports are within TCP range
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:42:22 +00:00
Cursor AgentandTheo Browne 6ab19a1970 Harden static asset path resolution and cwd normalization
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:41:35 +00:00
Cursor AgentandTheo Browne 5c6834db05 Resolve relative cwd args against parser launch directory
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:36:20 +00:00
Cursor AgentandTheo Browne e773e60486 Clarify T3_NO_OPEN truthy variants in CLI help text
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:35:03 +00:00
Cursor AgentandTheo Browne 9bd8e7b1db Normalize session cwd matching for bootstrap reuse
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:34:23 +00:00
Cursor AgentandTheo Browne b688456810 Cover Uint8Array websocket request decoding in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:32:20 +00:00
Cursor AgentandTheo Browne 61ddbacb77 Make static web server shutdown idempotent
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:31:35 +00:00
Cursor AgentandTheo Browne 35b83d45b0 Handle websocket close-before-open failures in adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:30:52 +00:00
Cursor AgentandTheo Browne 99c9dee1b1 Make runtime server close path concurrency-safe
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:29:34 +00:00
Cursor AgentandTheo Browne 7cd846a5ed Cleanup runtime resources when websocket startup fails
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:28:30 +00:00
Cursor AgentandTheo Browne c99e231578 Assert bootstrap project name derivation in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:25:48 +00:00
Cursor AgentandTheo Browne a60abc3bb5 Unref terminal timeout watchdog timer
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:24:54 +00:00
Cursor AgentandTheo Browne 3db1ffe8a9 Assert unauthorized clients receive no websocket messages
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:22:43 +00:00
Cursor AgentandTheo Browne 01759eefcb Hoist shell.openInEditor input schema for reuse
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:22:02 +00:00
Cursor AgentandTheo Browne 86fcc2a949 Cover trimmed positional cwd argument parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:21:26 +00:00
Cursor AgentandTheo Browne 223f4063ec Enforce non-empty positional cwd arguments in CLI parser
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:20:54 +00:00
Cursor AgentandTheo Browne b2d7c19868 Cover malformed error-response tolerance in ws adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:17:55 +00:00
Cursor AgentandTheo Browne 0f6dd6a3ed Assert websocket hello payload in smoke test handshake
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:16:50 +00:00
Cursor AgentandTheo Browne cfd273e78f Cover idempotent runtime server shutdown in integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:16:04 +00:00
Cursor AgentandTheo Browne 14fcd1acc4 Cover websocket binaryType configuration in adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:15:20 +00:00
Cursor AgentandTheo Browne 7ba2ef2027 Cover websocket recovery after open-event connection failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:14:47 +00:00
Cursor AgentandTheo Browne baf36427b3 Cover unknown agent session write and kill runtime behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:14:14 +00:00
Cursor AgentandTheo Browne a9fbb004bf Cover shell cursor open path in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:13:32 +00:00
Cursor AgentandTheo Browne 9c3b44edf4 Cover dialogs.pickFolder response contract in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:12:59 +00:00
Cursor AgentandTheo Browne abe616bda8 Cover shell file-manager open path in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:12:20 +00:00
Cursor AgentandTheo Browne b869dc61b4 Cover websocket reconnect behavior after socket close
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:11:40 +00:00
Cursor AgentandTheo Browne 4f48f21186 Cover invalid providers interrupt and stop payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:11:09 +00:00
Cursor AgentandTheo Browne 7e196a74dd Reset failed websocket connect attempts for retry
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:08:58 +00:00
Cursor AgentandTheo Browne d068a0c1fc Strengthen smoke-test app.health payload assertions
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:08:05 +00:00
Cursor AgentandTheo Browne e01496a19c Handle websocket constructor failures in browser adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:07:14 +00:00
Cursor AgentandTheo Browne 694818e5b3 Cover websocket responses with unknown request ids
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:06:20 +00:00
Cursor AgentandTheo Browne be2f37526f Assert hello protocol version in runtime integration test
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:05:44 +00:00
Cursor AgentandTheo Browne 0a83664bbd Cover non-zero terminal exit semantics in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:05:15 +00:00
Cursor AgentandTheo Browne 4d90913dcb Cover unknown T3_NO_OPEN values as disabled
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:04:34 +00:00
Cursor AgentandTheo Browne 13801292f2 Cover websocket adapter recovery after request timeouts
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:04:01 +00:00
Cursor AgentandTheo Browne 02c653535a Cover websocket request timeout rejection in adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:03:29 +00:00
Cursor AgentandTheo Browne 7a515bc5e4 Cover providers.listSessions success path in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:02:38 +00:00
Cursor AgentandTheo Browne cef4be1258 Force-kill timed-out terminal commands when SIGTERM is ignored
Co-authored-by: Theo Browne <[email protected]>
2026-02-10 00:01:48 +00:00
Cursor AgentandTheo Browne ec24213db7 Cover terminal.run cwd execution semantics in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:59:40 +00:00
Cursor AgentandTheo Browne 4d7fdad80b Cover T3_NO_OPEN yes-value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:59:03 +00:00
Cursor AgentandTheo Browne 3787530124 Cover terminal timeout behavior in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:58:31 +00:00
Cursor AgentandTheo Browne 114ba314ec Refactor runtime agent-event polling helper in tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:57:45 +00:00
Cursor AgentandTheo Browne 123a7a62bc Assert full app.health payload in runtime integration test
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:57:15 +00:00
Cursor AgentandTheo Browne 4eeb87d476 Cover agent write and kill lifecycle in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:56:50 +00:00
Cursor AgentandTheo Browne 582561232e Cover agent output and exit event streaming in runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:56:15 +00:00
Cursor AgentandTheo Browne 2d9e88e0cf Cover todo mutation lifecycle in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:55:16 +00:00
Cursor AgentandTheo Browne 04f619491c Cover terminal.run success path in runtime integration tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:54:43 +00:00
Cursor AgentandTheo Browne 3e2d282d58 Test ws adapter recovery from blob decode failures
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:52:15 +00:00
Cursor AgentandTheo Browne b20067263b Guard ws adapter decode path against async message errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:51:35 +00:00
Cursor AgentandTheo Browne f04d1204f9 Guard runtime websocket sends against state races
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:50:58 +00:00
Cursor AgentandTheo Browne 8f2e258849 Assert hello launchCwd metadata in runtime test
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:50:19 +00:00
Cursor AgentandTheo Browne ac6bae97fb Cover T3_NO_OPEN on-value parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:49:46 +00:00
Cursor AgentandTheo Browne 2bd2fe2869 Unref bootstrap session timeout timer
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:49:11 +00:00
Cursor AgentandTheo Browne db8a36fc74 Cover case-insensitive T3_NO_OPEN parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:48:33 +00:00
Cursor AgentandTheo Browne ee7ff3a849 Document flexible T3_NO_OPEN truthy values
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:48:01 +00:00
Cursor AgentandTheo Browne f3a1e40fce Use WebSocket.OPEN constant for runtime send guard
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:47:26 +00:00
Cursor AgentandTheo Browne 74a5c87bac Support truthy T3_NO_OPEN environment values
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:46:44 +00:00
Cursor AgentandTheo Browne 53b815b194 Reuse shared TextDecoder in ws adapter message parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:45:59 +00:00
Cursor AgentandTheo Browne 33c3cb9a81 Clear bootstrap startup timeout on session resolution
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:45:26 +00:00
Cursor AgentandTheo Browne 2f6d8d790d Cover invalid providers.startSession payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:43:18 +00:00
Cursor AgentandTheo Browne 77a2256347 Cover invalid providers.sendTurn payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:42:45 +00:00
Cursor AgentandTheo Browne d747326096 Cover invalid provider respond decision payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:42:11 +00:00
Cursor AgentandTheo Browne c020e23735 Cover provider control error propagation in ws adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:41:36 +00:00
Cursor AgentandTheo Browne 6e9fae8c56 Cover bootstrap error passthrough in runtime and ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:41:00 +00:00
Cursor AgentandTheo Browne e4fdcf59d1 Expand ws adapter tests for provider turn-control methods
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:40:07 +00:00
Cursor AgentandTheo Browne 6ffbb138c7 Cover invalid agent.spawn payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:37:50 +00:00
Cursor AgentandTheo Browne 1ba6f29f58 Cover dialogs and agent method mappings in ws adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:37:18 +00:00
Cursor AgentandTheo Browne e0a29a17ba Cover invalid todos.toggle payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:35:20 +00:00
Cursor AgentandTheo Browne c06af1b25e Cover invalid terminal.run payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:34:47 +00:00
Cursor AgentandTheo Browne 0e1f3844bf Cover invalid shell.openInEditor payload errors
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:34:12 +00:00
Cursor AgentandTheo Browne ff82a2c6c2 Cover todo mutation request mappings in ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:33:35 +00:00
Cursor AgentandTheo Browne 8e429e52f1 Extend ws adapter tests for terminal and provider methods
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:31:03 +00:00
Cursor AgentandTheo Browne 167e97cf65 Expand ws adapter tests for bootstrap and shell methods
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:30:32 +00:00
Cursor AgentandTheo Browne edb3d89959 Expand runtime tests for token encoding and cwd normalization
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:29:47 +00:00
Cursor AgentandTheo Browne e5065c9664 Cover app.health request mapping in ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:28:01 +00:00
Cursor AgentandTheo Browne 5012c6af70 Cover authorized single-client replacement path
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:27:32 +00:00
Cursor AgentandTheo Browne f3ac685f1c Assert agent event unsubscribe behavior in ws adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:26:59 +00:00
Cursor AgentandTheo Browne 770af97034 Cover agent event subscriber paths in ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:26:33 +00:00
Cursor AgentandTheo Browne 2b3e44046c Test ws adapter provider-event subscription lifecycle
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:25:45 +00:00
Cursor AgentandTheo Browne 4e36ebaea0 Cover runtime tolerance for malformed client messages
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:24:26 +00:00
Cursor AgentandTheo Browne bed026aed1 Cover ws adapter tolerance for malformed server messages
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:23:56 +00:00
Cursor AgentandTheo Browne 811e4e0365 Cover blob message decoding in ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:23:26 +00:00
Cursor AgentandTheo Browne ffc03e7efe Cover arraybuffer responses in ws adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:23:02 +00:00
Cursor AgentandTheo Browne 601fc201f0 Cover runtime auth token trimming semantics
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:22:37 +00:00
Cursor AgentandTheo Browne 2937134836 Cover whitespace equals-style cwd rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:21:51 +00:00
Cursor AgentandTheo Browne 6afafe9c20 Cover empty equals-style web port values
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:21:28 +00:00
Cursor AgentandTheo Browne 5757cd144c Cover empty equals-style backend port values
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:21:07 +00:00
Cursor AgentandTheo Browne a1f0ac0724 Cover short CLI flag aliases in parser tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:20:48 +00:00
Cursor AgentandTheo Browne 51c8517395 Add ws adapter test for connection failure path
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:20:26 +00:00
Cursor AgentandTheo Browne f7f9f144e7 Cover ws native API singleton caching behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:19:58 +00:00
Cursor AgentandTheo Browne 45fcdef07f Cover no-auth websocket connection behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:19:36 +00:00
Cursor AgentandTheo Browne 6bde37d6cf Document websocket token rejection behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:19:10 +00:00
Cursor AgentandTheo Browne 37cd2b696b Cover missing --cwd value parsing error
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:18:55 +00:00
Cursor AgentandTheo Browne b708a4ec89 Test missing backend and web port values
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:18:35 +00:00
Cursor AgentandTheo Browne 0cf6572336 Test ws adapter handling of hello prelude messages
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:18:11 +00:00
Cursor AgentandTheo Browne d4bd385419 Verify wrong-token websocket rejection paths
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:17:45 +00:00
Cursor AgentandTheo Browne ce6e47e35d Validate non-empty runtime websocket auth token
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:15:48 +00:00
Cursor AgentandTheo Browne e9cbb40c3d Cover whitespace-only cwd flag rejection
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:15:09 +00:00
Cursor AgentandTheo Browne f67a82e93c Document single-client websocket runtime policy
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:14:44 +00:00
Cursor AgentandTheo Browne 5816b37e5c Test trimmed --cwd argument parsing
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:14:21 +00:00
Cursor AgentandTheo Browne b5a830b328 Cover websocket disconnect rejection in adapter tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:13:53 +00:00
Cursor AgentandTheo Browne 2cb6ed9615 Add ws adapter test for structured error responses
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:13:30 +00:00
Cursor AgentandTheo Browne 8bd155f790 Cover arraybuffer websocket request decoding
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:13:04 +00:00
Cursor AgentandTheo Browne a73b95ae73 Ensure unauthorized websocket clients cannot evict active session
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:12:40 +00:00
Cursor AgentandTheo Browne cfe32a9623 Test ws adapter default runtime URL fallback
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:12:05 +00:00
Cursor AgentandTheo Browne 85ecef6fd6 Handle websocket send failures in browser adapter
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:11:38 +00:00
Cursor AgentandTheo Browne 133b0abd56 Assert unauthorized websocket rejection in smoke test
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:10:16 +00:00
Cursor AgentandTheo Browne f5e2112bf5 Decode non-string websocket client payloads
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:09:45 +00:00
Cursor AgentandTheo Browne 8ba5a22d45 Cover invalid backend env port parsing in CLI tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:09:01 +00:00
Cursor AgentandTheo Browne a5b1268ad4 Ensure smoke-test child shutdown cannot hang
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:08:43 +00:00
Cursor AgentandTheo Browne 5787d9cc25 Harden smoke test startup and ws token assertions
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:07:18 +00:00
Cursor AgentandTheo Browne ba30900df9 Assert tokenized ws URL in runtime auth test
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:05:42 +00:00
Cursor AgentandTheo Browne 0b9fbd7a7c Reject empty --cwd values in CLI parser
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:05:09 +00:00
Cursor AgentandTheo Browne 6185784ea2 Require ephemeral websocket token for CLI runtime
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:04:03 +00:00
Cursor AgentandTheo Browne a00269cab6 Validate environment port variables strictly
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:01:18 +00:00
Cursor AgentandTheo Browne 0600372cdd Drop useCallback from theme hook
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 23:00:28 +00:00
Cursor AgentandTheo Browne 709d9984c9 Remove ChatView useMemo-derived state wrappers
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:59:54 +00:00
Cursor AgentandTheo Browne ed2ef7d178 Support positional cwd argument for t3 CLI
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:55:59 +00:00
Cursor AgentandTheo Browne f153feb623 Eliminate lint warnings and remove await-in-loop patterns
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:53:58 +00:00
Cursor AgentandTheo Browne ff65c1356f Document automatic default port retry behavior
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:50:10 +00:00
Cursor AgentandTheo Browne 51d61e4894 Auto-retry default ports when startup hits EADDRINUSE
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:49:45 +00:00
Cursor AgentandTheo Browne ebefed3567 Improve startup errors with actionable port conflict guidance
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:46:55 +00:00
Cursor AgentandTheo Browne e6540e7f2d Resolve CLI version from package metadata with tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:45:13 +00:00
Cursor AgentandTheo Browne c263ff67ed Reduce redundant useMemo/useCallback around native API access
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:43:56 +00:00
Cursor AgentandTheo Browne f1841006c3 Add runtime health polling and sidebar offline indicator
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:42:11 +00:00
Cursor AgentandTheo Browne 6cc4e616bb Surface runtime connectivity errors in renderer bootstrap
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:40:23 +00:00
Cursor AgentandTheo Browne 39adcb6f04 Deduplicate bootstrap fallback state across repeated requests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:38:14 +00:00
Cursor AgentandTheo Browne 9ca17fd398 Add runtime app.health API and smoke-test health check
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:34:36 +00:00
Cursor AgentandTheo Browne e2a8f16e9e Harden CLI startup cleanup and error propagation
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:32:39 +00:00
Cursor AgentandTheo Browne b06d25073e Support --version and strict CLI port validation
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:30:47 +00:00
Cursor AgentandTheo Browne b53656c055 Refresh README wording for runtime provider dispatch
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:28:51 +00:00
Cursor AgentandTheo Browne cb29c60edb Run t3 smoke test in CI quality pipeline
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:28:26 +00:00
Cursor AgentandTheo Browne 283177f852 Make bootstrap timeout configurable for faster tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:27:54 +00:00
Cursor AgentandTheo Browne 10e0622019 Add t3 smoke-test script and root runner
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:27:16 +00:00
Cursor AgentandTheo Browne dec8db5155 Document t3 CLI flags in quickstart
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:26:08 +00:00
Cursor AgentandTheo Browne 4bffbf086f Add CLI argument parsing and help coverage
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:25:45 +00:00
Cursor AgentandTheo Browne f1b5e8ee06 Cap bootstrap session startup latency and expand runtime tests
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:23:53 +00:00
Cursor AgentandTheo Browne f72970d0cc Add websocket runtime integration tests and lifecycle fixes
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:21:56 +00:00
Cursor AgentandTheo Browne f85db4e56d Add websocket client request timeouts and binary-safe decoding
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:19:20 +00:00
Cursor AgentandTheo Browne d9ec69477b Make prepack independent of PATH bun setup
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:16:51 +00:00
Cursor AgentandTheo Browne 9e804c3c85 Handle launcher opener failures and add no-open mode
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:14:37 +00:00
Cursor AgentandTheo Browne e58c71a30e Make bootstrap resilient when codex startup fails
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:12:27 +00:00
Cursor AgentandTheo Browne 29aeea5bdb Harden t3 packaging for npx distribution
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:08:41 +00:00
Cursor AgentandTheo Browne 6dc4c80bc9 Replace Electron shell with t3 websocket browser architecture
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:03:50 +00:00
Cursor AgentandTheo Browne cf568902cd Add renderer websocket native API adapter and bootstrap flow
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 21:52:30 +00:00
Cursor AgentandTheo Browne 1f4ff504bb Add t3 websocket runtime server and CLI launcher
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 21:49:33 +00:00
Cursor AgentandTheo Browne 6614b93ccc Add websocket transport contracts and app bootstrap API
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 21:46:02 +00:00
233 changed files with 19436 additions and 33435 deletions

No files matched your search

+3 -8
View File
@@ -8,7 +8,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
name: Lint, Typecheck, Test
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -41,10 +41,5 @@ jobs:
- name: Test
run: bun run test
- name: Build desktop pipeline
run: bun run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
- name: Smoke Test (t3 runtime)
run: bun run --cwd apps/t3 build && bun run smoke-test
-1
View File
@@ -3,7 +3,6 @@
"ignorePatterns": [
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
"ignorePatterns": ["dist", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
+3 -3
View File
@@ -5,7 +5,7 @@ Move model alias/default normalization into `packages/contracts` so desktop and
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `packages/runtime-core/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
@@ -22,7 +22,7 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- `resolveModelSlug`
- `DEFAULT_MODEL`
2. Export model utilities from `packages/contracts/src/index.ts`.
3. Update `apps/desktop/src/codexAppServerManager.ts` to replace local alias map/helper.
3. Update `packages/runtime-core/src/codexAppServerManager.ts` to replace local alias map/helper.
4. Update `apps/renderer/src/model-logic.ts` to wrap or re-export shared functions.
5. Update tests:
- Move/duplicate normalization tests to contracts.
@@ -38,5 +38,5 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- No duplicated alias/default map in runtime-core and renderer.
- Shared model utilities are contract-tested.
+13 -13
View File
@@ -1,37 +1,37 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
# Plan: Strengthen Typed WS RPC Boundaries in Runtime Server
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
Replace loose payload casting in runtime RPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- `apps/t3/src/runtimeApiServer.ts` should avoid payload casts and parse all unknown input at the RPC boundary.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
- Runtime WebSocket RPC registration and method dispatch.
- Optional shared helper for method-level parse/dispatch registration.
## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
1. Add RPC helper utility (e.g. `apps/t3/src/rpcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
2. Refactor provider IPC handlers in `apps/desktop/src/main.ts` to use:
2. Refactor provider RPC handlers in `apps/t3/src/runtimeApiServer.ts` to use:
- `providerSessionStartInputSchema.parse`
- `providerSendTurnInputSchema.parse`
- `providerInterruptTurnInputSchema.parse`
- `providerStopSessionInputSchema.parse`
3. Apply same pattern to agent/terminal handlers where possible.
4. Add tests for handler parsing failure paths (invalid payloads).
3. Apply same pattern to app/todo/agent/terminal/shell handlers where possible.
4. Add tests for parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change IPC error shape/messages.
- Refactor can subtly change RPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual invalid payload check from renderer/devtools to confirm fast failure.
- Manual invalid payload check from websocket client/devtools to confirm fast failure.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
- No runtime handler uses `payload as Parameters<...>`.
- All websocket RPC entrypoints parse unknown payloads at boundary.
+2 -2
View File
@@ -4,7 +4,7 @@
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- `packages/runtime-core/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
- Session state transitions
@@ -12,7 +12,7 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Runtime-core provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
+4 -4
View File
@@ -4,18 +4,18 @@
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- `packages/runtime-core/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Desktop provider logging behavior.
- App shutdown integration.
- Runtime-core provider logging behavior.
- Runtime server shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
2. Call `providerManager.dispose()` from app shutdown path in `apps/desktop/src/main.ts`.
2. Call `providerManager.dispose()` from app shutdown path in `apps/t3/src/runtimeApiServer.ts` close flow.
3. Optional: change log format to JSON lines with stable fields.
4. Optional: per-session log files under `.logs/providers/`.
@@ -4,11 +4,11 @@
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- `packages/runtime-core/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Runtime-core process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
@@ -1,74 +0,0 @@
# Branch/Environment Picker in ChatView Input
## Summary
Add a secondary toolbar below the ChatView input area (similar to Codex UI) that lets users select the target branch and environment mode (Local vs New worktree) before sending their first message.
## UX
- A toolbar appears **below** the input form (always visible when it's a git repo)
- Two controls:
1. **Environment mode** (left side): toggles between "Local" and "New worktree" — **locked after first message** (no longer clickable, just shows current mode as label)
2. **Branch picker** (right side): dropdown showing local branches — **always changeable**, even after messages are sent
- If not a git repo, the toolbar is hidden entirely (thread uses project cwd as-is)
## Changes
### 0. Install `@tanstack/react-query` in `apps/renderer`
Add dependency + wrap app in `QueryClientProvider`.
### 1. `apps/renderer/src/store.ts` — MODIFY
Add a new action to the reducer:
```ts
| { type: "SET_THREAD_BRANCH"; threadId: string; branch: string | null; worktreePath: string | null }
```
Reducer case updates `branch` and `worktreePath` on the thread.
### 2. `apps/renderer/src/components/ChatView.tsx` — MODIFY
**Fetch branches** via `useQuery`:
```ts
const branchQuery = useQuery({
queryKey: ["git-branches", activeProject?.cwd],
queryFn: () => api.git.listBranches({ cwd: activeProject!.cwd }),
enabled: !!activeProject,
});
```
**Local state:**
- `envMode: "local" | "worktree"` — environment mode (local component state)
**UI:** Below the `<form>`, render a toolbar bar (hidden if `!branchQuery.data?.isRepo`):
- Left side: env mode button ("Local" / "New worktree") — disabled after first message (locked in)
- Right side: branch dropdown from `branchQuery.data.branches`
- Both styled like existing model picker (small text, chevron, dropdown menus)
**Behavior:**
- Branch picker is always active — changing branch dispatches `SET_THREAD_BRANCH` immediately
- Env mode is only clickable when `activeThread.messages.length === 0`. After first message, it becomes a static label showing the locked-in mode
- On first send (`onSend`): if `envMode === "worktree"` and a branch is selected, call `api.git.createWorktree` before starting the session, then dispatch `SET_THREAD_BRANCH` with the worktreePath
- `ensureSession` already uses `activeThread.worktreePath ?? activeProject.cwd`
### Files to modify
1. `apps/renderer/package.json` — add `@tanstack/react-query`
2. `apps/renderer/src/main.tsx` (or App entry) — wrap in `QueryClientProvider`
3. `apps/renderer/src/store.ts` — add `SET_THREAD_BRANCH` action
4. `apps/renderer/src/components/ChatView.tsx` — branch/env picker UI with `useQuery`
## Verification
1. `turbo build` — compiles
2. Create a new thread → branch bar appears below input with "Local" + current branch
3. Change branch in dropdown → branch updates on thread
4. Toggle "New worktree" → send message → worktree created, session uses worktree cwd
5. After first message: env mode label locks to "Worktree" (not clickable), branch picker still works
6. Non-git project → no branch bar shown
-99
View File
@@ -1,99 +0,0 @@
# Git Flows Integration Tests
## Overview
Real integration tests that run actual git commands against temporary repos. No mocking.
## Step 1: Extract git functions into `apps/desktop/src/git.ts`
The git functions (`listGitBranches`, `createGitWorktree`, `removeGitWorktree`, `createGitBranch`, `checkoutGitBranch`, `initGitRepo`) and their helper `runTerminalCommand` are currently private in `main.ts`. Extract them into a new `apps/desktop/src/git.ts` module with named exports.
`main.ts` will import and re-use them — no behavior change, just moving code.
**Files modified:**
- `apps/desktop/src/git.ts` — new file with all git functions exported
- `apps/desktop/src/main.ts` — import from `./git` instead of defining inline
## Step 2: Create `apps/desktop/src/git.test.ts`
Integration tests using real temp git repos. Each test group creates a fresh temp directory with `git init`, makes commits, creates branches as needed, and cleans up after.
### Setup/teardown pattern
```ts
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
listGitBranches,
createGitBranch,
checkoutGitBranch,
createGitWorktree,
removeGitWorktree,
initGitRepo,
} from "./git";
// Helper: run a raw git command in a dir (for test setup, not under test)
// Helper: create an initial commit (git needs at least one commit for branches)
```
### Test groups
**1. initGitRepo**
- Creates a valid git repo in a temp dir
- listGitBranches reports `isRepo: true` after init
**2. listGitBranches**
- Returns `isRepo: false` for non-git directory
- Returns the current branch with `current: true`
- Sorts current branch first
- Lists multiple branches after creating them
- `isDefault` is false when no remote (no origin/HEAD)
**3. checkoutGitBranch**
- Checks out an existing branch (current flag moves)
- Throws when branch doesn't exist
- Throws when checkout would overwrite uncommitted changes (dirty working tree)
**4. createGitBranch**
- Creates a new branch (appears in listGitBranches)
- Throws when branch already exists
**5. createGitWorktree + removeGitWorktree**
- Creates a worktree directory at the expected path
- Worktree has the correct branch checked out
- Throws when branch is already checked out in another worktree
- removeGitWorktree cleans up the worktree
**6. Full flow: local branch checkout**
- init → commit → create branch → checkout → verify current
**7. Full flow: worktree creation from selected branch**
- init → commit → create branch → create worktree → verify worktree dir exists and has correct branch
**8. Full flow: thread switching simulation**
- init → commit → create branch-a, branch-b → checkout a → checkout b → checkout a → verify current matches
**9. Full flow: checkout conflict**
- init → commit → create branch → modify file (unstaged) → checkout other branch → expect error
## Verification
```bash
# Run the git integration tests
cd apps/desktop && bun run test
# Or just the git test file
npx vitest run apps/desktop/src/git.test.ts
```
-103
View File
@@ -1,103 +0,0 @@
# Git Flows Test Plan
## Overview
Add tests for git branch/worktree flows. Two files:
1. **Extend** `apps/renderer/src/store.test.ts` — reducer tests for `SET_THREAD_BRANCH`
2. **Create** `apps/renderer/src/git-flows.test.ts` — flow logic tests
All tests are pure Vitest unit tests (no React rendering). They test the reducer directly and simulate handler logic via sequential reducer dispatches + mocked API calls.
## File 1: `apps/renderer/src/store.test.ts` (extend)
Add `describe("SET_THREAD_BRANCH reducer")` with 6 tests:
- Sets branch + worktreePath atomically
- Clears both to null
- Updates branch while preserving worktreePath
- Does not affect other threads (multi-thread state)
- No-op for nonexistent thread id
- Does not mutate messages, error, or session fields
Uses existing `makeThread`, `makeState` factories.
## File 2: `apps/renderer/src/git-flows.test.ts` (new)
### Factories
- `makeThread()`, `makeState()`, `makeSession()` — same pattern as store.test.ts
- `makeBranch()` — creates `GitBranch` objects
- `makeMessage()` — creates `ChatMessage` objects
- `makeGitApi()` — returns `{ checkout, createWorktree, createBranch, listBranches }` with `vi.fn()` mocks
### Test groups (~30 tests total)
**1. Local branch checkout flow** (2 tests)
- Successful checkout → SET_THREAD_BRANCH updates branch
- Checkout failure → SET_ERROR, branch unchanged
**2. Thread branch conflict on send** (3 tests)
- Two threads maintain independent branch state after SET_ACTIVE_THREAD
- Branch state preserved through multiple thread switches + updates
- Checkout failure on thread switch sets error only on target thread
**3. Worktree creation on send** (5 tests)
- First message in worktree mode → createWorktree → SET_THREAD_BRANCH with worktreePath
- No worktree when messages already exist
- No worktree in local envMode
- No worktree when worktreePath already set
- createWorktree failure → SET_ERROR, send aborted, no messages pushed
**4. Env mode locking** (4 tests)
- envLocked=false when no messages
- envLocked=true with messages
- Transitions false→true after PUSH_USER_MESSAGE
- Remains true after SET_ERROR and UPDATE_SESSION
**5. Auto-fill current branch** (3 tests)
- Dispatches SET_THREAD_BRANCH when thread has no branch and current branch exists
- Does not overwrite existing branch
- No-op when no branch is marked current
**6. Default branch detection** (2 tests)
- isDefault flag on branch objects
- current and isDefault can be on different branches
**7. Branch creation + checkout** (3 tests)
- Successful create + checkout updates branch
- createBranch failure → error, branch unchanged
- checkout failure after successful create → error, branch unchanged
**8. Session CWD resolution** (3 tests)
- Uses worktreePath when available
- cwdOverride takes precedence over worktreePath
- Falls back to project cwd when no worktree
**9. Error handling patterns** (4 tests)
- SET_ERROR sets error on correct thread
- SET_ERROR with null clears error
- Error on one thread doesn't affect others
- Error cleared before successful branch operations
## Verification
```bash
# Run all renderer tests
cd apps/renderer && bun run test
# Run just the new test file
npx vitest run apps/renderer/src/git-flows.test.ts
# Run just the store tests
npx vitest run apps/renderer/src/store.test.ts
```
@@ -1,115 +0,0 @@
# Git Integration: Branch Picker + Worktrees
## Summary
Add git integration to let users start new threads from a specific branch, optionally creating a git worktree for isolated agent work.
## UX Flow
- **Left click** "+ New thread" → immediately creates a thread (current behavior, unchanged)
- **Right click** "+ New thread" → opens a context menu with git options:
- List of local branches → clicking one creates a thread on that branch (uses project cwd)
- Each branch has a "worktree" sub-option → creates a worktree, then creates thread with worktree as cwd
- When thread has a worktree, the agent session uses the worktree path as its cwd
- If git fails (not a repo), context menu shows "Not a git repository" disabled item
## Changes
### 1. `packages/contracts/src/git.ts` — CREATE
New Zod schemas and types:
- `gitListBranchesInputSchema` — `{ cwd: string }`
- `gitCreateWorktreeInputSchema` — `{ cwd: string, branch: string, path?: string }`
- `gitRemoveWorktreeInputSchema` — `{ cwd: string, path: string }`
- `gitBranchSchema` — `{ name: string, current: boolean }`
- Result types for each
### 2. `packages/contracts/src/ipc.ts` — MODIFY
- Add 3 IPC channels: `git:list-branches`, `git:create-worktree`, `git:remove-worktree`
- Add `git` namespace to `NativeApi` with `listBranches`, `createWorktree`, `removeWorktree`
### 3. `packages/contracts/src/index.ts` — MODIFY
- Add `export * from "./git"`
### 4. `apps/desktop/src/main.ts` — MODIFY
Add 3 IPC handlers + helper functions:
- `listGitBranches()` — runs `git branch --no-color`, parses output into `{ name, current }[]`
- `createGitWorktree()` — runs `git worktree add <path> <branch>`, defaults path to `../{repo}-worktrees/{branch}`
- `removeGitWorktree()` — runs `git worktree remove <path>`
Reuses existing `runTerminalCommand()`.
### 5. `apps/desktop/src/preload.ts` — MODIFY
Add `git` namespace with 3 `ipcRenderer.invoke` calls.
### 6. `apps/renderer/src/types.ts` — MODIFY
Add to `Thread`:
```
branch: string | null
worktreePath: string | null
```
### 7. `apps/renderer/src/persistenceSchema.ts` — MODIFY
- Add optional `branch`/`worktreePath` to persisted thread schema (`.nullable().optional()` for backwards compat)
- Add V3 schema, update union
- Update `hydrateThread` to default new fields to `null`
- Update `toPersistedState` to serialize new fields
### 8. `apps/renderer/src/store.ts` — MODIFY
- Update persisted state key to v3, keep v2 as legacy fallback
### 9. `apps/renderer/src/components/Sidebar.tsx` — MODIFY (main UI work)
- Keep existing left-click `handleNewThread` unchanged (immediate thread creation)
- Add `onContextMenu` handler to "+ New thread" buttons (both global and per-project)
- On right-click: fetch branches via `api.git.listBranches`, show a custom context menu
- Context menu items: branch names, each with a nested option to create with worktree
- Clicking a branch → creates thread with `branch` set, title = branch name
- Clicking "with worktree" → calls `api.git.createWorktree` first, then creates thread with `worktreePath`
- Show branch badge on thread list items
- If not a git repo, show "Not a git repository" as disabled menu item
Context menu component: a positioned `<div>` with `position: fixed` anchored to the click position, dismissed on click-outside or Escape. Follows the existing dropdown pattern from ChatView's model picker.
### 10. `apps/renderer/src/components/ChatView.tsx` — MODIFY
- Line 157: use `activeThread.worktreePath ?? activeProject.cwd` as session cwd
- Show branch/worktree badge in header bar
## Implementation Order
1. `packages/contracts/src/git.ts` (new schemas)
2. `packages/contracts/src/ipc.ts` + `index.ts` (wire up channels)
3. `apps/desktop/src/main.ts` (git command handlers)
4. `apps/desktop/src/preload.ts` (bridge methods)
5. `apps/renderer/src/types.ts` (Thread type update)
6. `apps/renderer/src/persistenceSchema.ts` + `store.ts` (persistence migration)
7. `apps/renderer/src/components/Sidebar.tsx` (branch picker UI)
8. `apps/renderer/src/components/ChatView.tsx` (worktree cwd + badge)
## Edge Cases
- **Not a git repo**: `git branch` fails → context menu shows "Not a git repository" disabled item
- **Branch has slashes**: `feature/foo` → worktree dir becomes `feature-foo`
- **Worktree exists**: git error surfaces to user via inline error message in context menu
- **No persistence breakage**: `.nullable().optional()` fields parse fine with old data
## Verification
1. `turbo build` — confirm contracts/desktop/renderer all compile
2. Launch app, add a project pointing to a git repo
3. Click "+ New thread" → verify branch list loads
4. Select a branch, click Start → thread created with branch in title
5. Enable worktree checkbox, pick branch, Start → verify worktree directory created on disk
6. Send a message in worktree thread → verify agent runs in worktree cwd
7. Add a non-git project → verify graceful error, can still create thread
+12 -10
View File
@@ -1,8 +1,8 @@
# CLAUDE.md
# AGENTS.md
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
CodeThing is a minimal GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -16,20 +16,22 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `apps/t3`: Node CLI/runtime. Owns WebSocket server lifecycle, browser launch, and RPC routing.
- `apps/renderer`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket payloads, and model/session types.
- `packages/runtime-core`: Shared Node runtime services (`ProcessManager`, `TodoStore`, `ProviderManager`, `CodexAppServerManager`) used by `apps/t3`.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is the canonical runtime service source.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is the canonical runtime service source.
## Codex App Server (Important)
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
CodeThing is currently Codex-first. The `t3` runtime starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events into the renderer through the provider APIs.
How we use it in this codebase:
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
- Session startup/resume and turn lifecycle are brokered in `packages/runtime-core/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `packages/runtime-core/src/providerManager.ts`.
- Renderer consumes provider event streams via `nativeApi.providers.onEvent`.
Docs:
-101
View File
@@ -1,101 +0,0 @@
# Keybindings
T3 Code reads keybindings from:
- `~/.t3/keybindings.json`
The file must be a JSON array of rules:
```json
[
{ "key": "mod+g", "command": "terminal.toggle" },
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
```json
[
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
### Rule Shape
Each entry supports:
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): action ID
- `when` (optional): boolean expression controlling when the shortcut is active
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
### Available Commands
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
### Key Syntax
Supported modifiers:
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
- `cmd` / `meta`
- `ctrl` / `control`
- `shift`
- `alt` / `option`
Examples:
- `mod+j`
- `mod+shift+d`
- `ctrl+l`
- `cmd+k`
### `when` Conditions
Currently available context keys:
- `terminalFocus`
- `terminalOpen`
Supported operators:
- `!` (not)
- `&&` (and)
- `||` (or)
- parentheses: `(` `)`
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "terminalFocus || terminalOpen"`
Unknown condition keys evaluate to `false`.
### Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- That means precedence is across commands, not only within the same command.
+130 -81
View File
@@ -1,107 +1,156 @@
# T3 Code
# CodeThing (`t3`: Node + WebSocket + Browser)
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
CodeThing now runs as a local Node.js runtime that serves a browser UI and exposes a local WebSocket API.
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
Current implementation is:
## Architecture
1. Codex-first: connects to `codex app-server` and streams turn/item events.
2. Provider-ready: renderer speaks a provider abstraction so Claude Code can plug in later.
3. Typed end-to-end: contracts validate payloads across the WebSocket boundary.
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
## Quickstart
```bash
npx t3
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
On launch, `t3`:
1. starts a local WebSocket runtime (`127.0.0.1`),
2. serves the web UI in your browser,
3. auto-connects to your current working directory as the default project.
CLI flags:
- `--no-open[=bool]` — disable browser auto-open (supports `true/false`, `1/0`, `yes/no`, `on/off` in equals form).
- `-o, --open[=bool]` — force browser auto-open (supports `true/false`, `1/0`, `yes/no`, `on/off` in equals form; overrides `T3_NO_OPEN`).
- `--backend-port <port>` — set WebSocket runtime port.
- `--web-port <port>` — set web UI port.
- `--cwd <path>` — choose launch project directory (defaults to current directory).
- `<path>` — shorthand positional argument equivalent to `--cwd <path>`.
- `-- <path>` — treat following argument as path even if it starts with `-`.
- `--version` — print CLI version.
- `--help` — print CLI usage.
`--cwd` (or positional path) must be a non-empty value pointing to an existing directory; startup fails fast with a clear error otherwise.
Port values must be decimal integers in the range `1..65535`.
If default ports are busy, `t3` will automatically retry with the next available port pair unless ports are explicitly pinned via CLI flags or environment variables.
Optional environment variables:
- `T3_NO_OPEN=1` — start runtime without auto-opening a browser window (parses `true/false`, `1/0`, `yes/no`, `on/off`).
- `T3_BACKEND_PORT` — override local WebSocket runtime port (default `4317`).
- `T3_WEB_PORT` — override local web UI port (default `4318`).
Runtime command semantics:
- `terminal.run` executes in the launch directory when `cwd` is omitted.
- Relative `cwd` values for `terminal.run` and `shell.openInEditor` resolve from the launch directory.
- `terminal.run` and `shell.openInEditor` reject empty/whitespace, missing, or non-directory cwd targets with structured request errors.
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `/apps/t3`: CLI launcher + local WebSocket runtime server.
- `/apps/renderer`: React + Vite UI for session control, conversation, and protocol event stream.
- `/packages/contracts`: shared Zod schemas + TypeScript types for WS protocol, provider events, and API contracts.
- `/packages/runtime-core`: shared Node runtime services (`ProcessManager`, `TodoStore`, `ProviderManager`, `CodexAppServerManager`) consumed by `apps/t3`.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is now the sole source of runtime service implementations.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
- Authenticate Codex before running CodeThing (for example via API key or ChatGPT auth supported by Codex).
- CodeThing starts the server via `codex app-server` per session.
- Note: test suites use an in-process fake `codex app-server` shim, so CI/local tests do not require the real Codex CLI.
## Quick start
## Runtime boundary model
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Or from any project directory after publishing:
npx t3
```
## Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
- `t3` starts a localhost-only WebSocket server.
- Launch URLs include an ephemeral WebSocket token so only the opened browser session can attach.
- Connections missing the token (or using a wrong token) are rejected by the runtime.
- Connections with duplicate token query parameters are also rejected (even when duplicate values match) to avoid ambiguous auth parsing.
- Runtime auth token lookup is strict on the lowercase `token` query key; alternate key casing is rejected.
- Connections with unexpected query parameters are rejected (auth mode requires only `token`; no-auth mode allows no query params).
- WebSocket control connections are accepted only on the root runtime path (`/`) to keep the API surface narrow.
- Unauthorized websocket attempts close with code `4001` and reason `unauthorized`.
- Browser renderer talks through a typed `NativeApi` adapter over that WebSocket.
- Runtime currently enforces a single active browser client (new client replaces old one).
- When replaced by a newer connection, the previous active websocket is closed with code `4000`.
- Replacement closes use reason string `replaced-by-new-client` for deterministic client handling.
- Renderer websocket connection errors now preserve close metadata (`code`/`reason`) to improve reconnect diagnostics.
- Renderer normalizes close metadata before diagnostics (e.g. trims close reasons and ignores malformed close codes) for cleaner error messages.
- Renderer decodes websocket message payloads from strings, `ArrayBuffer`, `ArrayBufferView` (e.g. `Uint8Array`/`DataView`), and `Blob`.
- Renderer validates provider/agent event payload shapes before dispatch, ignoring malformed event payloads to keep client state stable.
- Renderer validates critical RPC success payload shapes (`app.health`, `app.bootstrap`, `providers.listSessions`, `dialogs.pickFolder`, plus terminal/todo/provider/agent control flows) and fails fast on malformed responses.
- In-flight renderer requests now surface unauthorized/replacement disconnect causes explicitly.
- Renderer also fails in-flight requests immediately on websocket `error` events (without waiting for close) for faster feedback.
- After reconnect, renderer ignores stale events from prior sockets (including provider and agent streams) to avoid cross-connection state corruption.
- Initial websocket connect failures now include detailed diagnostics from socket/open and constructor failures (including nested/string/cause-chain payload messages, with bounded-depth fallback for malformed/cyclic payloads).
- Subsequent requests automatically reconnect after close/error disconnects, including idle (no pending request) error scenarios.
- Renderer now proactively resets the websocket after request send failures, rejects any in-flight requests, and reconnects cleanly on later requests.
- Send-failure request errors now include non-Error payload details when available (for clearer diagnostics).
- Runtime validates request payloads with shared Zod contracts.
- Websocket RPC method names are centralized in shared contracts (`WS_NATIVE_API_METHODS`), and runtime dispatch validates method strings against that shared list.
- Runtime tests now assert that every declared websocket method is wired through the server dispatch path (preventing contract/runtime drift).
- Runtime and renderer both validate critical success payloads with shared contracts to prevent malformed envelope data from entering app state.
- Core transport schemas (provider/agent/todo/terminal/app payloads) are strict objects, so unexpected fields are rejected at the contract boundary.
- Runtime successful responses always include `result` (using `null` for void methods) to keep websocket envelopes schema-safe.
- Websocket event envelopes are channel-typed (`provider:event`, `agent:output`, `agent:exit`) and validated against shared payload schemas.
- Websocket protocol envelopes are strict (unexpected top-level fields are rejected) to keep RPC/event parsing deterministic.
- Websocket request envelope guards also cap request id/method lengths (currently 256 chars each); over-limit requests are treated as malformed and ignored.
- Runtime error envelopes are bounded (`code`/`message` max lengths) and oversized error text is normalized before sending to avoid protocol-invalid responses.
- Blank/whitespace-only websocket ids, methods, and error fields are rejected at schema boundaries.
- Codex execution sandbox policy (`read-only`, `workspace-write`, `danger-full-access`) is still selected per session startup options.
- Static HTML responses are served with `Cache-Control: no-store`; built `/assets/*` files are served with long-lived immutable cache headers.
- Static file success responses include `Accept-Ranges: bytes`, `Vary: Range`, deterministic `ETag` and `Last-Modified` validators, plus hardened browser headers (`X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Cross-Origin-Resource-Policy`, `Cross-Origin-Opener-Policy`).
- Static files support single-range byte requests (`Range: bytes=...`) with standards-compliant `206` / `416` behavior.
- Static range parsing tolerates optional separator whitespace (e.g. `Range: bytes = 0 - 1023`).
- Oversized suffix ranges are normalized to full-file spans (for example `bytes=-999999` on small assets).
- Static non-range requests support `If-None-Match` and `If-Modified-Since` conditional caching via `304 Not Modified`.
- Static range requests support `If-Range` semantics (matched validator keeps `206`; mismatched validator falls back to full `200` response).
- `If-None-Match` / `If-Modified-Since` preconditions are evaluated before range handling, so satisfied validators return `304` even when a `Range` header is present.
- Static precondition headers `If-Match` and `If-Unmodified-Since` are enforced with `412 Precondition Failed` semantics.
- Failed `If-Match` checks take precedence over cache validators (e.g. matching `If-None-Match` still results in `412` if `If-Match` fails).
- Failed `If-Unmodified-Since` checks also return `412` before cache-based `304` handling.
- Wildcard validators are supported where applicable (`If-None-Match: *`, `If-Match: *`).
- Strong/weak validator semantics follow HTTP rules: weak ETags participate in `If-None-Match` weak comparison, but are rejected for strong-only checks (`If-Match`, `If-Range`).
- `412` static precondition responses include validator headers (`ETag`, `Last-Modified`) and range capability metadata (`Accept-Ranges`, `Vary: Range`).
- `416` unsatisfiable-range responses include both range metadata and validators (`Content-Range`, `Accept-Ranges`, `Vary: Range`, `ETag`, `Last-Modified`).
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
CodeThing has a global runtime mode switch in the sidebar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
- `Full access` (default): starts new sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- `Approval required`: starts new sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
Mode changes apply across all threads. Existing live sessions are restarted so old and new threads use the selected mode.
## Scripts
- `bun run dev`: builds contracts, starts `t3` runtime, opens browser UI.
- `bun run build`: builds contracts, renderer static assets, and `t3` CLI bundle.
- `bun run typecheck`: strict TypeScript checks for all packages.
- `bun run test`: runs workspace tests.
- `bun run smoke-test`: runs end-to-end CLI/WebSocket smoke coverage (against the fake Codex app-server shim).
- `bun run --cwd apps/t3 dev`: run the CLI directly in dev mode.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
The renderer depends on `nativeApi.providers.*`:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
1. `startSession`
2. `sendTurn`
3. `interruptTurn`
4. `respondToRequest`
5. `stopSession`
6. `listSessions`
7. `onEvent`
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but currently returns a not-implemented runtime error.
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Runtime app utilities exposed via `nativeApi.app.*`:
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
1. `bootstrap`
2. `health`
+6 -17
View File
@@ -1,23 +1,12 @@
# TODO
## Small things
## TODO
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
- [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [ ] Insta focus input on new thread creation
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things
- [ ] Queueing messages
- [ ] External runners (i.e. running the cli on a mac mini)
- [ ] "Response" bar should ONLY appear on work completed
- [ ] "Response" bar should ONLY appear above the FINAL message in a series
- [ ] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
-1
View File
@@ -1 +0,0 @@
dist-electron/
-27
View File
@@ -1,27 +0,0 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "electron dist-electron/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "33.4.11"
},
"devDependencies": {
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"wait-on": "^8.0.2"
}
}
-31
View File
@@ -1,31 +0,0 @@
import { spawn } from "node:child_process";
import waitOn from "wait-on";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
});
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
});
child.on("exit", (code) => {
process.exit(code ?? 0);
});
-57
View File
@@ -1,57 +0,0 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
console.log("\nLaunching Electron smoke test...");
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
VITE_DEV_SERVER_URL: "",
ELECTRON_ENABLE_LOGGING: "1",
},
});
let output = "";
child.stdout.on("data", (chunk) => {
output += chunk.toString();
});
child.stderr.on("data", (chunk) => {
output += chunk.toString();
});
const timeout = setTimeout(() => {
child.kill();
}, 8_000);
child.on("exit", () => {
clearTimeout(timeout);
const fatalPatterns = [
"Cannot find module",
"MODULE_NOT_FOUND",
"Refused to execute",
"Uncaught Error",
"Uncaught TypeError",
"Uncaught ReferenceError",
];
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
if (failures.length > 0) {
console.error("\nDesktop smoke test failed:");
for (const failure of failures) {
console.error(` - ${failure}`);
}
console.error("\nFull output:\n" + output);
process.exit(1);
}
console.log("Desktop smoke test passed.");
process.exit(0);
});
-57
View File
@@ -1,57 +0,0 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
-26
View File
@@ -1,26 +0,0 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
-18
View File
@@ -1,18 +0,0 @@
import { execFileSync } from "node:child_process";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
-279
View File
@@ -1,279 +0,0 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
let backendPort = 0;
let backendAuthToken = "";
let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, "127.0.0.1", () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
resolve(port);
return;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
restartAttempt += 1;
console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
restartTimer = setTimeout(() => {
restartTimer = null;
startBackend();
}, delayMs);
}
function startBackend(): void {
if (isQuitting || backendProcess) return;
if (!fs.existsSync(BACKEND_ENTRY)) {
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
return;
}
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: "inherit",
});
backendProcess = child;
child.once("spawn", () => {
restartAttempt = 0;
});
child.on("error", (error) => {
if (backendProcess === child) {
backendProcess = null;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
if (backendProcess === child) {
backendProcess = null;
}
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
}
function stopBackend(): void {
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
const child = backendProcess;
backendProcess = null;
if (!child) return;
if (!child.killed) {
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 2_000).unref();
}
}
function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
ipcMain.removeHandler(CONFIRM_CHANNEL);
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
if (typeof message !== "string") {
return false;
}
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
if (!window) return null;
return new Promise<string | null>((resolve) => {
const menu = Menu.buildFromTemplate(
items.map((item) => ({
label: item.label,
click: () => resolve(item.id),
})),
);
menu.popup({
window,
callback: () => resolve(null),
});
});
});
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
return true;
} catch {
return false;
}
});
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
autoHideMenuBar: true,
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.once("ready-to-show", () => {
window.show();
});
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
}
window.on("closed", () => {
if (mainWindow === window) {
mainWindow = null;
}
});
return window;
}
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
registerIpcHandlers();
startBackend();
mainWindow = createWindow();
}
app.on("before-quit", () => {
isQuitting = true;
stopBackend();
});
app.whenReady().then(() => {
void bootstrap();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
-16
View File
@@ -1,16 +0,0 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
});
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
-21
View File
@@ -1,21 +0,0 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
-24
View File
@@ -1,24 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CodeThing</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
@@ -1,5 +1,5 @@
{
"name": "@t3tools/web",
"name": "@acme/renderer",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -11,32 +11,24 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"@acme/contracts": "workspace:*",
"highlight.js": "^11.11.1",
"lucide-react": "^0.564.0",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"rehype-highlight": "^7.0.2",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zod": "^3.24.1"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.1.4",
"@vitejs/plugin-react": "^4.3.4",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.3",
"vite": "^8.0.0-beta.12"
"vite": "^6.0.5"
}
}
+140
View File
@@ -0,0 +1,140 @@
import { useEffect, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
import Sidebar from "./components/Sidebar";
import { readNativeApi } from "./session-logic";
import { StoreProvider, useStore } from "./store";
function EventRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch]);
return null;
}
function BootstrapRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
let cancelled = false;
void api.app
.bootstrap()
.then((bootstrap) => {
if (cancelled) return;
dispatch({
type: "BOOTSTRAP_FROM_SERVER",
bootstrap,
});
})
.catch((error) => {
if (cancelled) return;
dispatch({
type: "SET_RUNTIME_ERROR",
error:
error instanceof Error
? error.message
: "Could not connect to the local t3 runtime.",
});
});
return () => {
cancelled = true;
};
}, [api, dispatch]);
return null;
}
function RuntimeHealthRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
let cancelled = false;
const checkHealth = async () => {
try {
await api.app.health();
if (cancelled) return;
dispatch({ type: "SET_RUNTIME_ERROR", error: null });
} catch (error) {
if (cancelled) return;
dispatch({
type: "SET_RUNTIME_ERROR",
error:
error instanceof Error
? error.message
: "Could not connect to the local t3 runtime.",
});
}
};
void checkHealth();
const interval = window.setInterval(() => {
void checkHealth();
}, 8_000);
return () => {
cancelled = true;
window.clearInterval(interval);
};
}, [api, dispatch]);
return null;
}
function Layout() {
const api = readNativeApi();
const { state } = useStore();
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">Local t3 runtime unavailable.</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<BootstrapRouter />
<RuntimeHealthRouter />
<EventRouter />
{state.runtimeError && state.projects.length === 0 && (
<div className="pointer-events-none fixed right-4 top-4 z-50 max-w-[440px] rounded-lg border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-100">
Runtime connection failed: {state.runtimeError}
</div>
)}
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
</div>
);
}
export default function App() {
return (
<StoreProvider>
<Layout />
</StoreProvider>
);
}
@@ -1,4 +1,3 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -14,7 +13,7 @@ const markdownComponents: Components = {
},
};
function ChatMarkdown({ text }: ChatMarkdownProps) {
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -27,5 +26,3 @@ function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
+986
View File
@@ -0,0 +1,986 @@
import {
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type ProviderApprovalDecision,
type ProviderEvent,
} from "@acme/contracts";
import {
type FormEvent,
Fragment,
type KeyboardEvent,
useEffect,
useRef,
useState,
} from "react";
import { EDITORS, type EditorId } from "@acme/contracts";
import { buildBootstrapInput } from "../historyBootstrap";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
MODEL_OPTIONS,
REASONING_OPTIONS,
resolveModelSlug,
} from "../model-logic";
import {
derivePhase,
deriveTimelineEntries,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
formatTimestamp,
readNativeApi,
} from "../session-logic";
import { useStore } from "../store";
import ChatMarkdown from "./ChatMarkdown";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
return `${formatTimestamp(createdAt)} • ${duration}`;
}
const FILE_MANAGER_LABEL = navigator.platform.includes("Mac")
? "Finder"
: navigator.platform.includes("Win")
? "Explorer"
: "Files";
function editorLabel(editor: (typeof EDITORS)[number]): string {
return editor.command ? editor.label : FILE_MANAGER_LABEL;
}
const LAST_EDITOR_KEY = "codething:last-editor";
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
if (tone === "tool") return "text-muted-foreground/70";
if (tone === "thinking") return "text-muted-foreground/50";
return "text-muted-foreground/40";
}
interface PendingApprovalCard {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
type SessionContinuityState = "resumed" | "new" | "fallback_new";
interface EnsuredSessionInfo {
sessionId: string;
resolvedThreadId: string | null;
continuityState: SessionContinuityState;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asRecord(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {
const pending = new Map<string, PendingApprovalCard>();
const ordered = events.toReversed();
for (const event of ordered) {
if (event.method === "session/closed" || event.method === "session/exited") {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asRecord(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
export default function ChatView() {
const { state, dispatch } = useStore();
const api = readNativeApi();
const [prompt, setPrompt] = useState("");
const [isSending, setIsSending] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
const [isEditorMenuOpen, setIsEditorMenuOpen] = useState(false);
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
});
const [selectedEffort, setSelectedEffort] = useState<string>(DEFAULT_REASONING);
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>([]);
const [nowTick, setNowTick] = useState(() => Date.now());
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const modelMenuRef = useRef<HTMLDivElement>(null);
const editorMenuRef = useRef<HTMLDivElement>(null);
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const phase = derivePhase(activeThread?.session ?? null);
const isWorking = phase === "running" || isSending || isConnecting;
const nowIso = new Date(nowTick).toISOString();
const modelOptions = MODEL_OPTIONS;
const workLogEntries = deriveWorkLogEntries(activeThread?.events ?? [], undefined);
const pendingApprovals = derivePendingApprovals(activeThread?.events ?? []);
const assistantCompletionByItemId = (() => {
const map = new Map<string, string>();
const ordered = [...(activeThread?.events ?? [])].toReversed();
for (const event of ordered) {
if (event.method !== "item/completed") continue;
if (!event.itemId) continue;
map.set(event.itemId, event.createdAt);
}
return map;
})();
const timelineEntries = deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries);
const completionSummary = (() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (workLogEntries.length === 0) return null;
if (
typeof activeThread.latestTurnDurationMs === "number" &&
Number.isFinite(activeThread.latestTurnDurationMs) &&
activeThread.latestTurnDurationMs >= 0
) {
return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`;
}
const elapsed = formatElapsed(
activeThread.latestTurnStartedAt,
activeThread.latestTurnCompletedAt,
);
return elapsed ? `Worked for ${elapsed}` : null;
})();
const completionDividerBeforeEntryId = (() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (workLogEntries.length === 0) return null;
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
if (Number.isNaN(turnStartedAt)) return null;
const entry = timelineEntries.find((timelineEntry) => {
if (timelineEntry.kind !== "message") return false;
if (timelineEntry.message.role !== "assistant") return false;
const messageAt = Date.parse(timelineEntry.message.createdAt);
return !Number.isNaN(messageAt) && messageAt >= turnStartedAt;
});
return entry?.id ?? null;
})();
const runtimeSessionConfig =
state.runtimeMode === "full-access"
? ({
approvalPolicy: "never",
sandboxMode: "danger-full-access",
} as const)
: ({
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
} as const);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
if (!api) return;
const sessionIds = state.threads
.map((t) => t.session)
.filter((s): s is NonNullable<typeof s> => s !== null && s.status !== "closed")
.map((s) => s.sessionId);
if (sessionIds.length === 0) return;
setIsSwitchingRuntimeMode(true);
try {
await Promise.all(
sessionIds.map((id) => api.providers.stopSession({ sessionId: id }).catch(() => undefined)),
);
} finally {
setIsSwitchingRuntimeMode(false);
}
};
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messageCount]);
useEffect(() => {
if (phase !== "running") return;
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [phase, workLogCount]);
// Auto-resize textarea
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.style.height = "auto";
ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`;
}, [prompt]);
useEffect(() => {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 250);
return () => {
window.clearInterval(timer);
};
}, [phase]);
useEffect(() => {
if (!isModelMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!modelMenuRef.current) return;
if (event.target instanceof Node && !modelMenuRef.current.contains(event.target)) {
setIsModelMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isModelMenuOpen]);
useEffect(() => {
if (!isEditorMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!editorMenuRef.current) return;
if (event.target instanceof Node && !editorMenuRef.current.contains(event.target)) {
setIsEditorMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isEditorMenuOpen]);
// Cmd+O / Ctrl+O to open in last-used editor
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
if (api && activeProject) {
e.preventDefault();
void api.shell.openInEditor(activeProject.cwd, lastEditor);
}
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, lastEditor]);
const openInEditor = (editorId: EditorId) => {
if (!api || !activeProject) return;
void api.shell.openInEditor(activeProject.cwd, editorId);
setLastEditor(editorId);
localStorage.setItem(LAST_EDITOR_KEY, editorId);
setIsEditorMenuOpen(false);
};
const ensureSession = async (): Promise<EnsuredSessionInfo | null> => {
if (!api || !activeThread || !activeProject) return null;
if (
activeThread.session &&
activeThread.session.status !== "closed" &&
activeThread.session.status !== "error"
) {
const sessionThreadId = activeThread.session.threadId ?? null;
const continuityState: SessionContinuityState =
activeThread.codexThreadId === null
? "new"
: sessionThreadId === activeThread.codexThreadId
? "resumed"
: "fallback_new";
return {
sessionId: activeThread.session.sessionId,
resolvedThreadId: sessionThreadId,
continuityState,
} satisfies EnsuredSessionInfo;
}
const priorCodexThreadId = activeThread.codexThreadId;
setIsConnecting(true);
try {
const session = await api.providers.startSession({
provider: "codex",
cwd: activeProject.cwd || undefined,
model: selectedModel || undefined,
resumeThreadId: priorCodexThreadId ?? undefined,
approvalPolicy: runtimeSessionConfig.approvalPolicy,
sandboxMode: runtimeSessionConfig.sandboxMode,
});
dispatch({
type: "UPDATE_SESSION",
threadId: activeThread.id,
session,
});
const resolvedThreadId = session.threadId ?? null;
const continuityState: SessionContinuityState =
priorCodexThreadId === null
? "new"
: resolvedThreadId === priorCodexThreadId
? "resumed"
: "fallback_new";
return {
sessionId: session.sessionId,
resolvedThreadId,
continuityState,
};
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to connect.",
});
return null;
} finally {
setIsConnecting(false);
}
};
const onSend = async (e: FormEvent) => {
e.preventDefault();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed) return;
// Auto-title from first message
if (activeThread.messages.length === 0) {
const title = trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
title,
});
}
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: null,
});
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
});
const previousMessages = activeThread.messages;
setPrompt("");
const sessionInfo = await ensureSession();
if (!sessionInfo) return;
setIsSending(true);
try {
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
const input = shouldBootstrap
? buildBootstrapInput(previousMessages, trimmed, PROVIDER_SEND_TURN_MAX_INPUT_CHARS).text
: trimmed;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
input,
model: selectedModel || undefined,
effort: selectedEffort || undefined,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to send message.",
});
} finally {
setIsSending(false);
}
};
const onInterrupt = async () => {
if (!api || !activeThread?.session) return;
await api.providers.interruptTurn({
sessionId: activeThread.session.sessionId,
turnId: activeThread.session.activeTurnId,
});
};
const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeThread?.session) return;
setRespondingRequestIds((existing) =>
existing.includes(requestId) ? existing : [...existing, requestId],
);
try {
await api.providers.respondToRequest({
sessionId: activeThread.session.sessionId,
requestId,
decision,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
};
const onModelSelect = (model: string) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
setIsModelMenuOpen(false);
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
}
};
// Empty state: no active thread
if (!activeThread) {
return (
<div className="flex flex-1 flex-col bg-background text-muted-foreground/40">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-sm">Select a thread or create a new one to get started.</p>
</div>
</div>
</div>
);
}
return (
<div className="flex flex-1 flex-col bg-background">
{/* Top bar */}
<header className="drag-region flex items-center justify-between border-b border-border px-5 pt-[28px] pb-3">
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
{activeProject && (
<div className="relative" ref={editorMenuRef}>
<button
type="button"
className="rounded-md px-2 py-1 text-[10px] text-muted-foreground/40 transition-colors duration-150 hover:text-muted-foreground/60"
onClick={() => setIsEditorMenuOpen((v) => !v)}
>
Open in&hellip;
</button>
{isEditorMenuOpen && (
<div className="absolute right-0 top-full z-50 mt-1 min-w-[120px] rounded-md border border-border bg-popover py-1 shadow-xl">
{EDITORS.map((editor) => (
<button
key={editor.id}
type="button"
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-foreground hover:bg-accent"
onClick={() => openInEditor(editor.id)}
>
{editorLabel(editor)}
{editor.id === lastEditor && (
<kbd className="ml-auto text-[9px] text-muted-foreground/40">
{navigator.platform.includes("Mac") ? "\u2318O" : "Ctrl+O"}
</kbd>
)}
</button>
))}
</div>
)}
</div>
)}
{/* Diff toggle */}
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
state.diffOpen
? "bg-accent text-foreground"
: "text-muted-foreground/40 hover:text-muted-foreground/60"
}`}
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
Diff
</button>
</div>
</header>
{/* Error banner */}
{activeThread.error && (
<div className="mx-4 mt-3 rounded-lg border border-rose-400/20 bg-rose-900/20 px-3 py-2 text-xs text-rose-200">
{activeThread.error}
</div>
)}
{pendingApprovals.length > 0 && (
<div className="mx-4 mt-3 space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<div
key={approval.requestId}
className="rounded-lg border border-amber-300/20 bg-amber-500/[0.07] px-3 py-2"
>
<p className="text-xs font-medium text-amber-100">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</p>
{approval.detail && (
<p
className="mt-1 truncate font-mono text-[11px] text-amber-100/75"
title={approval.detail}
>
{approval.detail}
</p>
)}
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</button>
<button
type="button"
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</button>
<button
type="button"
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</button>
<button
type="button"
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</button>
</div>
</div>
);
})}
</div>
)}
{/* Messages */}
<div className="flex-1 overflow-y-auto px-5 py-4">
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => (
<Fragment key={timelineEntry.id}>
{timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
(completionDividerBeforeEntryId === timelineEntry.id ||
timelineEntries[index - 1]?.kind === "work") && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
{timelineEntry.kind === "work" ? (
<div className="flex items-start gap-2 py-0.5 pl-1.5">
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
>
{timelineEntry.entry.detail ? (
<>
{timelineEntry.entry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={timelineEntry.entry.detail}
>
{timelineEntry.entry.detail}
</span>
</>
) : (
timelineEntry.entry.label
)}
</p>
</div>
) : timelineEntry.message.role === "user" ? (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
) : (
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
{timelineEntry.message.streaming && (
<div className="pt-1.5">
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/[0.08] px-2 py-0.5 text-[10px] text-sky-100/90">
<span className="inline-flex gap-1">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:150ms]" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:300ms]" />
</span>
<span>Thinking</span>
</span>
</div>
)}
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
)}
</Fragment>
))}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</div>
{/* Input bar */}
<div className="px-5 pb-4 pt-2">
<form onSubmit={onSend} className="mx-auto max-w-3xl">
<div className="group rounded-[20px] border border-border bg-card transition-colors duration-200 focus-within:border-ring">
{/* Textarea area */}
<div className="px-4 pt-4 pb-2">
<textarea
ref={textareaRef}
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
rows={2}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onKeyDown={onKeyDown}
placeholder={
phase === "disconnected" ? "Ask for follow-up changes" : "Ask anything..."
}
disabled={isSending || isConnecting}
/>
</div>
{/* Bottom toolbar */}
<div className="flex items-center justify-between px-3 pb-3">
<div className="flex items-center gap-1">
{/* Model picker */}
<div className="relative" ref={modelMenuRef}>
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
onClick={() => setIsModelMenuOpen((open) => !open)}
>
<span className="max-w-[180px] truncate">{selectedModel}</span>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-50"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{isModelMenuOpen && (
<div className="absolute bottom-full left-0 z-20 mb-2 w-[320px] rounded-2xl border border-border bg-popover/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
<p className="px-2 py-1 text-[11px] text-muted-foreground/70">Select model</p>
<div className="max-h-72 overflow-y-auto">
{modelOptions.map((model) => {
const isSelected = model === selectedModel;
return (
<button
key={model}
type="button"
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left font-mono text-sm transition-colors duration-150 ${
isSelected
? "bg-accent text-foreground"
: "text-foreground/90 hover:bg-accent"
}`}
onClick={() => onModelSelect(model)}
>
<span className="truncate">{model}</span>
<span
className={`pt-0.5 text-sm ${
isSelected ? "text-foreground" : "text-transparent"
}`}
>
✓
</span>
</button>
);
})}
</div>
</div>
)}
</div>
{/* Divider */}
<div className="mx-0.5 h-4 w-px bg-border" />
{/* Reasoning effort */}
<label
className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
htmlFor="reasoning-effort"
>
<span>{selectedEffort.charAt(0).toUpperCase() + selectedEffort.slice(1)}</span>
<select
id="reasoning-effort"
className="absolute opacity-0 w-0 h-0"
value={selectedEffort}
onChange={(event) => setSelectedEffort(event.target.value)}
>
{REASONING_OPTIONS.map((effort) => (
<option key={effort} value={effort} className="bg-popover">
{effort}
{effort === DEFAULT_REASONING ? " (default)" : ""}
</option>
))}
</select>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-50"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</label>
{/* Divider */}
<div className="mx-0.5 h-4 w-px bg-border" />
{/* Runtime mode toggle */}
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
disabled={isSwitchingRuntimeMode}
onClick={() =>
void handleRuntimeModeChange(
state.runtimeMode === "full-access" ? "approval-required" : "full-access",
)
}
title={
state.runtimeMode === "full-access"
? "Full access — click to require approvals"
: "Approval required — click for full access"
}
>
{state.runtimeMode === "full-access" ? (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
width="10"
height="7"
rx="1.5"
stroke="currentColor"
strokeWidth="1.3"
/>
<path
d="M9.5 5.5V4a2.5 2.5 0 0 0-5 0"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
) : (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
width="10"
height="7"
rx="1.5"
stroke="currentColor"
strokeWidth="1.3"
/>
<path
d="M4.5 5.5V4a2.5 2.5 0 0 1 5 0v1.5"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
)}
<span>{state.runtimeMode === "full-access" ? "Full access" : "Supervised"}</span>
</button>
</div>
{/* Right side: send / stop button */}
<div className="flex items-center gap-2">
{phase === "running" ? (
<button
type="button"
className="flex h-8 w-8 items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105"
onClick={() => void onInterrupt()}
aria-label="Stop generation"
>
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="currentColor"
aria-hidden="true"
>
<rect x="2" y="2" width="8" height="8" rx="1.5" />
</svg>
</button>
) : (
<button
type="submit"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
disabled={isSending || isConnecting || !prompt.trim()}
aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
}
>
{isConnecting || isSending ? (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
className="animate-spin"
aria-hidden="true"
>
<circle
cx="7"
cy="7"
r="5.5"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeDasharray="20 12"
/>
</svg>
) : (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
aria-hidden="true"
>
<path
d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</button>
)}
</div>
</div>
</div>
</form>
</div>
</div>
);
}
@@ -0,0 +1,52 @@
import { useStore } from "../store";
export default function DiffPanel() {
const { dispatch } = useStore();
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div className="drag-region flex items-center justify-between border-b border-border px-4 pt-[28px] pb-3">
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
type="button"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
<div className="flex-1 overflow-y-auto p-4">
<div className="space-y-3">
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="mb-2 flex items-center gap-2">
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
M
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
</div>
<div className="space-y-0.5 font-mono text-[11px]">
<div className="text-red-400/60">- const oldValue = "hello";</div>
<div className="text-emerald-400/60">+ const newValue = "world";</div>
</div>
</div>
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="flex items-center gap-2">
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
A
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
</div>
</div>
</div>
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
Diff integration coming soon
</p>
</div>
</aside>
);
}
+330
View File
@@ -0,0 +1,330 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import type { Project } from "../types";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
if (status === "running") return "Working";
if (status === "connecting") return "Connecting";
return null;
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = readNativeApi();
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const handleAddProject = () => {
const cwd = newCwd.trim();
if (!cwd) return;
const name = cwd.split("/").findLast((segment) => segment.length > 0) ?? "project";
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
setNewCwd("");
setAddingProject(false);
};
const handleNewThread = (projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
setNewCwd(pickedPath);
} finally {
setIsPickingFolder(false);
}
};
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const isNewThreadShortcut =
event.metaKey &&
event.shiftKey &&
!event.ctrlKey &&
!event.altKey &&
event.key.toLowerCase() === "o";
if (!isNewThreadShortcut) return;
const target = event.target;
if (target instanceof HTMLElement) {
const tagName = target.tagName;
if (
target.isContentEditable ||
tagName === "INPUT" ||
tagName === "TEXTAREA" ||
tagName === "SELECT"
) {
return;
}
}
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [dispatch, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
{/* Drag region / traffic light space */}
<div className="drag-region h-[52px] shrink-0" />
{/* Branding */}
<div className="flex items-center gap-2 px-4 pb-4">
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
CT
</div>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
CodeThing
</span>
{state.runtimeError && (
<span className="rounded-full border border-rose-400/30 bg-rose-500/10 px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider text-rose-100">
Offline
</span>
)}
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
</div>
{/* New thread (global) */}
<div className="px-3 pb-3">
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={() => {
if (state.projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = state.projects[0];
if (firstProject) handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
New thread
</button>
</div>
{/* Project list */}
<nav className="flex-1 overflow-y-auto px-2">
{state.projects.map((project) => {
const threads = state.threads
.filter((t) => t.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
return (
<div key={project.id} className="mb-1">
{/* Project header */}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
>
<span className="text-[10px] text-muted-foreground/70">
{project.expanded ? "▼" : "▶"}
</span>
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
</button>
{/* Threads */}
{project.expanded && (
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusLabel(thread.session?.status);
return (
<button
key={thread.id}
type="button"
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() =>
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: thread.id,
})
}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{threadStatus && (
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
<span className="hidden xl:inline">{threadStatus}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</button>
);
})}
{/* New thread within project */}
<button
type="button"
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => handleNewThread(project.id)}
>
<span>+</span> New thread
</button>
</div>
)}
</div>
);
})}
{state.projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
Add one to get started.
</div>
)}
</nav>
{/* Add project form */}
{addingProject ? (
<div className="border-t border-border p-3">
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
Add project
</p>
<input
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
placeholder="/path/to/project"
value={newCwd}
onChange={(e) => setNewCwd(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAddProject();
if (e.key === "Escape") setAddingProject(false);
}}
/>
{api && (
<button
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-2">
<button
type="button"
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
onClick={handleAddProject}
>
Add
</button>
<button
type="button"
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
onClick={() => setAddingProject(false)}
>
Cancel
</button>
</div>
</div>
) : (
<div className="border-t border-border p-3">
<button
type="button"
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
onClick={() => setAddingProject(true)}
>
+ Add project
</button>
</div>
)}
</aside>
);
}
@@ -91,32 +91,4 @@ describe("buildBootstrapInput", () => {
expect(result.omittedCount).toBe(1);
expect(result.truncated).toBe(true);
});
it("captures user image attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: "u-image",
role: "user",
text: "",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What does this error mean?",
1_500,
);
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
});
@@ -18,34 +18,8 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function buildMessageBlock(message: ChatMessage): string {
const text = message.text;
const attachments = attachmentSummary(message);
if (text && attachments) {
return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;
}
if (text) {
return `${messageRoleLabel(message)}:\n${text}`;
}
if (attachments) {
return `${messageRoleLabel(message)}:\n${attachments}`;
}
return `${messageRoleLabel(message)}:\n(empty message)`;
return `${messageRoleLabel(message)}:\n${message.text}`;
}
function finalizeWithPrompt(
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
import { useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
const STORAGE_KEY = "t3code:theme";
const STORAGE_KEY = "codething:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
@@ -28,7 +28,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
document.documentElement.classList.toggle("dark", isDark);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
document.documentElement.offsetHeight;
void document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
@@ -75,11 +75,11 @@ export function useTheme() {
const resolvedTheme: "light" | "dark" =
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
const setTheme = (next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
applyTheme(next, true);
emitChange();
}, []);
};
// Keep DOM in sync on mount/change
useEffect(() => {
@@ -11,6 +11,19 @@
--color-info-foreground: var(--info-foreground);
--color-info: var(--info);
--color-destructive-foreground: var(--destructive-foreground);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
@@ -48,7 +61,7 @@
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground relative;
@apply bg-background text-foreground;
}
}
@@ -70,8 +83,8 @@
--card-foreground: var(--color-neutral-800);
--popover: var(--color-white);
--popover-foreground: var(--color-neutral-800);
--primary: oklch(0.488 0.217 264);
--primary-foreground: var(--color-white);
--primary: var(--color-neutral-800);
--primary-foreground: var(--color-neutral-50);
--secondary: --alpha(var(--color-black) / 4%);
--secondary-foreground: var(--color-neutral-800);
--muted: --alpha(var(--color-black) / 4%);
@@ -81,7 +94,20 @@
--destructive: var(--color-red-500);
--border: --alpha(var(--color-black) / 8%);
--input: --alpha(var(--color-black) / 10%);
--ring: oklch(0.488 0.217 264);
--ring: var(--color-neutral-400);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
--sidebar-primary: oklch(0.21 0.006 285.885);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.967 0.001 286.375);
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
--sidebar-border: oklch(0.92 0.004 286.32);
--sidebar-ring: oklch(0.705 0.015 286.067);
--destructive-foreground: var(--color-red-700);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
@@ -98,8 +124,8 @@
--card-foreground: var(--color-neutral-100);
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
--popover-foreground: var(--color-neutral-100);
--primary: oklch(0.588 0.217 264);
--primary-foreground: var(--color-white);
--primary: var(--color-neutral-100);
--primary-foreground: var(--color-neutral-800);
--secondary: --alpha(var(--color-white) / 4%);
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
@@ -109,7 +135,20 @@
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--ring: oklch(0.588 0.217 264);
--ring: var(--color-neutral-500);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.552 0.016 285.938);
--destructive-foreground: var(--color-red-400);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
@@ -122,12 +161,7 @@
body {
font-family:
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
margin: 0;
padding: 0;
min-height: 100vh;
@@ -190,20 +224,6 @@ input {
background: rgba(255, 255, 255, 0.18);
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar > .slider {
border-radius: 3px;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical > .slider {
width: 6px !important;
left: 0 !important;
}
/* Reasoning select -- clickable label surface */
label:has(> select#reasoning-effort) {
position: relative;
@@ -1,6 +1,5 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "@xterm/xterm/css/xterm.css";
import "highlight.js/styles/github-dark.css";
import App from "./App";
File renamed without changes.
@@ -3,8 +3,7 @@ export {
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
} from "@acme/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export type ReasoningEffort = (typeof REASONING_OPTIONS)[number];
export const DEFAULT_REASONING: ReasoningEffort = "high";
export const DEFAULT_REASONING = "high";
+172
View File
@@ -0,0 +1,172 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
it("returns null for invalid payloads", () => {
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
expect(hydratePersistedState("not-json", false)).toBeNull();
});
it("migrates the legacy default model to the current default", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.2-codex",
messages: [
{
id: "m-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, true);
expect(hydrated).not.toBeNull();
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("filters unknown project references and repairs active thread", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Valid thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
{
id: "t-2",
projectId: "p-missing",
title: "Dangling thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-2",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated).not.toBeNull();
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("hydrates runtime mode from v3 payload", () => {
const payload = JSON.stringify({
version: 3,
runtimeMode: "approval-required",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [],
activeThreadId: null,
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
});
describe("toPersistedState", () => {
it("writes v4 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.version).toBe(4);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
messages: thread.messages,
createdAt: thread.createdAt,
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
if (!persistedThread) return;
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import { DEFAULT_RUNTIME_MODE, type Project, type RuntimeMode, type Thread } from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
const persistedProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
});
const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
});
const persistedStateBodySchema = z.object({
projects: z.array(persistedProjectSchema),
threads: z.array(persistedThreadSchema),
activeThreadId: z.string().min(1).nullable(),
});
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
export const persistedStateV1Schema = persistedStateBodySchema.extend({
version: z.literal(1).optional(),
});
export const persistedStateV2Schema = persistedStateBodySchema.extend({
version: z.literal(2).optional(),
});
export const persistedStateV3Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(3).optional(),
});
export const persistedStateV4Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(4).optional(),
});
const persistedStateSchema = z.union([
persistedStateV4Schema,
persistedStateV3Schema,
persistedStateV2Schema,
persistedStateV1Schema,
]);
export interface PersistedStoreSnapshot {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
}
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
if (!isLegacyPayload) {
return model;
}
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
}
function hydrateProject(
project: z.infer<typeof persistedProjectSchema>,
isLegacyPayload: boolean,
): Project {
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
};
}
function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
return {
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
session: null,
messages: thread.messages.map((message) => ({
...message,
streaming: false,
})),
events: [],
error: null,
createdAt: thread.createdAt,
};
}
export function hydratePersistedState(
raw: string,
isLegacyPayload: boolean,
): PersistedStoreSnapshot | null {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
return null;
}
const parsedState = persistedStateSchema.safeParse(parsedJson);
if (!parsedState.success) {
return null;
}
const projects = parsedState.data.projects.map((project) =>
hydrateProject(project, isLegacyPayload),
);
const projectIds = new Set(projects.map((project) => project.id));
const threads = parsedState.data.threads
.map((thread) => hydrateThread(thread, isLegacyPayload))
.filter((thread) => projectIds.has(thread.projectId));
const hasActiveThread = Boolean(
parsedState.data.activeThreadId &&
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
);
return {
projects,
threads,
activeThreadId: hasActiveThread ? parsedState.data.activeThreadId : (threads[0]?.id ?? null),
runtimeMode:
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV4Schema> {
return {
version: 4,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
messages: thread.messages,
createdAt: thread.createdAt,
})),
activeThreadId: state.activeThreadId,
runtimeMode: state.runtimeMode,
};
}
@@ -1,12 +1,9 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTurnDiffSummaries,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -137,7 +134,7 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
it("logs turn completion with elapsed time", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
@@ -157,38 +154,7 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
expect(entries[0]?.label).toBe("Turn complete in 10s");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
@@ -263,45 +229,11 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
expect(entries.map((entry) => entry.label)).toEqual([
"Turn complete in 8.0s",
"Tool call complete",
"Tool call",
]);
});
it("preserves full tool-call detail text without data truncation", () => {
@@ -325,50 +257,6 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
@@ -395,306 +283,6 @@ describe("deriveWorkLogEntries", () => {
});
});
describe("deriveTurnDiffSummaries", () => {
it("tracks completed turns and links them to assistant message completion", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-file-change",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-file-change",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/a.ts",
kind: "modified",
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
},
],
},
},
}),
makeEvent({
id: "evt-turn-diff-updated",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
threadId: "thr-1",
turnId: "turn-1",
diff: [
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old",
"+new",
"diff --git a/src/b.ts b/src/b.ts",
"@@ -0,0 +1 @@",
"+created",
].join("\n"),
},
}),
makeEvent({
id: "evt-agent-msg",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: {
id: "msg-1",
type: "agentMessage",
text: "Done",
},
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
makeEvent({
id: "evt-turn-2-file-change",
method: "item/completed",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-file-change-2",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/unfinished.ts",
kind: "modified",
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
},
],
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
expect(summaries[0]?.unifiedDiff).toContain("diff --git a/src/a.ts b/src/a.ts");
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(summaries[0]?.files[0]?.kind).toBe("modified");
expect(summaries[0]?.files[0]?.additions).toBe(1);
expect(summaries[0]?.files[0]?.deletions).toBe(1);
});
it("includes completed turns even when no fileChange tool events were emitted", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.files).toEqual([]);
});
it("keeps newest diff data when older events provide stale values", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-diff-old",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1 @@",
"-old",
"+older",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-diff-new",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1 @@",
"-old",
"+newest",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.unifiedDiff).toContain("+newest");
expect(summaries[0]?.unifiedDiff).not.toContain("+older");
});
});
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
it("splits a multi-file patch into sorted per-file entries", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/src/b.ts b/src/b.ts",
"@@ -1 +1 @@",
"-old-b",
"+new-b",
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old-a",
"+new-a",
].join("\n"),
);
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(files[0]?.diff).toContain("diff --git a/src/a.ts b/src/a.ts");
expect(files[1]?.diff).toContain("diff --git a/src/b.ts b/src/b.ts");
expect(files[0]?.additions).toBe(1);
expect(files[0]?.deletions).toBe(1);
});
it("parses git headers when file paths include ` b/`", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
"--- a/subdir b/example.ts",
"+++ b/subdir b/example.ts",
"@@ -1 +1 @@",
"-old",
"+new",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/example.ts");
});
it("parses git header fallback for binary diffs with ` b/` in path", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/image.png b/subdir b/image.png",
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/image.png");
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
@@ -1,6 +1,6 @@
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { getOrCreateWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,21 +11,9 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
export function readNativeApi() {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
return window.nativeApi ?? getOrCreateWsNativeApi();
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
@@ -33,18 +21,10 @@ export function asObject(value: unknown): Record<string, unknown> | undefined {
return value as Record<string, unknown>;
}
function asArray(value: unknown): unknown[] | undefined {
return Array.isArray(value) ? value : undefined;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
@@ -86,13 +66,6 @@ export interface WorkLogEntry {
tone: "thinking" | "tool" | "info" | "error";
}
export interface PendingApproval {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
export type TimelineEntry =
| {
id: string;
@@ -107,60 +80,12 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
@@ -203,28 +128,15 @@ function itemTypeMeta(type: string): {
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.prompt),
asString(item?.command),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
@@ -237,7 +149,7 @@ function extractDetail(
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
@@ -255,16 +167,14 @@ function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCan
return null;
}
const label = isCompleted ? `${meta.label} complete` : meta.label;
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
@@ -307,7 +217,7 @@ function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
};
}
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
function entryFromNotification(event: ProviderEvent, turnStartedAt: number): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
@@ -320,22 +230,32 @@ function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
const eventAt = Date.parse(event.createdAt);
const durationMs =
Number.isNaN(turnStartedAt) || Number.isNaN(eventAt) || eventAt < turnStartedAt
? undefined
: eventAt - turnStartedAt;
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
label:
status === "failed"
? "Turn failed"
: durationMs !== undefined
? `Turn complete in ${formatDuration(durationMs)}`
: "Turn complete",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
tone: status === "failed" ? "error" : "info",
};
}
const lifecycleEntry = entryFromItemLifecycle(event);
if (lifecycleEntry) return lifecycleEntry;
if (event.method.startsWith("item/")) return null;
return null;
@@ -375,56 +295,19 @@ export function deriveWorkLogEntries(
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
if (turnId) {
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
continue;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
continue;
}
}
}
const fromRequest = entryFromRequest(event);
@@ -433,7 +316,7 @@ export function deriveWorkLogEntries(
continue;
}
const fromNotification = entryFromNotification(event);
const fromNotification = entryFromNotification(event, turnStartedAt);
if (fromNotification) {
entries.push(fromNotification);
continue;
@@ -448,278 +331,6 @@ export function deriveWorkLogEntries(
return entries;
}
interface MutableTurnDiffSummary {
turnId: string;
completedAt: string | undefined;
status: string | undefined;
assistantMessageId: string | undefined;
unifiedDiff: string | undefined;
filesByPath: Map<string, TurnDiffFileChange>;
}
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
if (event.method !== "item/completed") {
return [];
}
const item = asObject(asObject(event.payload)?.item);
const itemType = normalizeItemType(asString(item?.type));
if (itemType !== "file change") {
return [];
}
const changes = asArray(item?.changes) ?? [];
const parsed: TurnDiffFileChange[] = [];
for (const rawChange of changes) {
const change = asObject(rawChange);
if (!change) continue;
const diff = normalizeDetail(asString(change.diff));
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
if (!path) continue;
const additions = asNumber(change.additions);
const deletions = asNumber(change.deletions);
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
const kind = normalizeDetail(asString(change.kind));
parsed.push({
path,
...(kind ? { kind } : {}),
...(diff ? { diff } : {}),
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
});
}
return parsed;
}
function mergeTurnDiffFileChange(
byPath: Map<string, TurnDiffFileChange>,
incoming: TurnDiffFileChange,
): void {
const existing = byPath.get(incoming.path);
if (!existing) {
byPath.set(incoming.path, incoming);
return;
}
if (existing.kind === undefined && incoming.kind !== undefined) {
existing.kind = incoming.kind;
}
if (existing.diff === undefined && incoming.diff !== undefined) {
existing.diff = incoming.diff;
}
if (existing.additions === undefined && incoming.additions !== undefined) {
existing.additions = incoming.additions;
}
if (existing.deletions === undefined && incoming.deletions !== undefined) {
existing.deletions = incoming.deletions;
}
}
function parsePathFromDiff(diff: string): string | undefined {
const normalized = diff.replace(/\r\n/g, "\n");
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
if (bPath && bPath[1]) return bPath[1];
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
if (gitHeader && gitHeader[1]) return gitHeader[1];
const direct = normalized.match(/^\+\+\+ (.+)$/m);
if (!direct || !direct[1] || direct[1] === "/dev/null") {
return undefined;
}
return direct[1];
}
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
const normalized = diff.replace(/\r\n/g, "\n");
const byPath = new Map<string, string>();
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
if (headerMatches.length === 0) {
const path = parsePathFromDiff(normalized);
if (path) {
byPath.set(path, normalized.trim());
}
return byPath;
}
for (let index = 0; index < headerMatches.length; index += 1) {
const match = headerMatches[index];
if (!match) continue;
const start = match.index ?? 0;
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
const segment = normalized.slice(start, nextStart).trim();
const path = parsePathFromDiff(segment);
if (!path || segment.length === 0) continue;
byPath.set(path, segment);
}
return byPath;
}
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
return Array.from(fileDiffsByPath.entries())
.map(([path, fileDiff]) => {
const stat = countDiffStat(fileDiff);
return {
path,
diff: fileDiff,
additions: stat.additions,
deletions: stat.deletions,
};
})
.toSorted((a, b) => a.path.localeCompare(b.path));
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
if (summaries.length === 0) {
return {};
}
const sorted = [...summaries].toSorted((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return a.completedAt.localeCompare(b.completedAt);
}
return aTime - bTime;
});
const next: Record<string, number> = {};
let fallbackTurnCount = 1;
for (const summary of sorted) {
if (typeof summary.checkpointTurnCount === "number") {
next[summary.turnId] = summary.checkpointTurnCount;
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
continue;
}
next[summary.turnId] = fallbackTurnCount;
fallbackTurnCount += 1;
}
return next;
}
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
if (!patch) {
return { additions: 0, deletions: 0 };
}
let additions = 0;
let deletions = 0;
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
if (line.startsWith("+")) {
additions += 1;
continue;
}
if (line.startsWith("-")) {
deletions += 1;
}
}
return { additions, deletions };
}
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
const ordered =
events.length < 2 ||
Number.isNaN(firstEventAt) ||
Number.isNaN(lastEventAt) ||
firstEventAt >= lastEventAt
? events
: [...events].toReversed();
const byTurnId = new Map<string, MutableTurnDiffSummary>();
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
const existing = byTurnId.get(turnId);
if (existing) return existing;
const next: MutableTurnDiffSummary = {
turnId,
completedAt: undefined,
status: undefined,
assistantMessageId: undefined,
unifiedDiff: undefined,
filesByPath: new Map<string, TurnDiffFileChange>(),
};
byTurnId.set(turnId, next);
return next;
};
for (const event of ordered) {
const turnId = eventTurnId(event);
if (!turnId) continue;
const summary = ensureSummary(turnId);
if (event.method === "turn/completed") {
if (summary.completedAt === undefined) {
summary.completedAt = event.createdAt;
}
const turn = asObject(asObject(event.payload)?.turn);
if (summary.status === undefined) {
summary.status = normalizeDetail(asString(turn?.status));
}
}
if (event.method === "item/completed") {
const item = asObject(asObject(event.payload)?.item);
if (asString(item?.type) === "agentMessage") {
const itemId = normalizeDetail(asString(item?.id));
if (itemId && summary.assistantMessageId === undefined) {
summary.assistantMessageId = itemId;
}
}
}
if (event.method === "turn/diff/updated" && summary.unifiedDiff === undefined) {
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
if (diff) {
summary.unifiedDiff = diff;
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
}
for (const file of parseFileChangeEntriesFromEvent(event)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
const summaries: TurnDiffSummary[] = [];
for (const summary of byTurnId.values()) {
if (!summary.completedAt) continue;
summaries.push({
turnId: summary.turnId,
completedAt: summary.completedAt,
...(summary.status ? { status: summary.status } : {}),
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
a.path.localeCompare(b.path),
),
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
});
}
summaries.sort((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return b.completedAt.localeCompare(a.completedAt);
}
return bTime - aTime;
});
return summaries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
+181
View File
@@ -0,0 +1,181 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import type { Thread } from "./types";
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-09T00:00:01.000Z",
method: "thread/started",
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-local-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
session: makeSession(),
messages: [],
events: [],
error: null,
createdAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeState(thread: Thread): AppState {
return {
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: thread.id,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
}
describe("store reducer thread continuity", () => {
it("bootstraps project and active thread from runtime response", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const session = makeSession({
sessionId: "sess-bootstrap",
threadId: "thr-bootstrap",
});
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session,
},
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.cwd).toBe("/workspace");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.session?.sessionId).toBe("sess-bootstrap");
expect(next.activeThreadId).toBe(next.threads[0]?.id ?? null);
});
it("surfaces bootstrap errors on the active thread", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session: makeSession({
sessionId: "sess-bootstrap-error",
status: "error",
}),
bootstrapError: "Timed out waiting for initialize.",
},
});
expect(next.threads[0]?.error).toBe("Timed out waiting for initialize.");
});
it("stores runtime connection errors separately from thread errors", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_RUNTIME_ERROR",
error: "Connection refused",
});
expect(next.runtimeError).toBe("Connection refused");
expect(next.threads[0]?.error).toBeNull();
});
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
makeThread({
session: null,
}),
);
const next = reducer(state, {
type: "UPDATE_SESSION",
threadId: "thread-local-1",
session: makeSession({ threadId: "thr_123" }),
});
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
payload: { thread: { id: "thr_backfilled" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
});
it("surfaces thread id mismatches without overwriting stored identity", () => {
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/started",
threadId: "thr_unexpected",
payload: { turn: { id: "turn-1" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_expected");
expect(next.threads[0]?.error).toContain("Thread identity mismatch");
});
});
+410
View File
@@ -0,0 +1,410 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import type { AppBootstrapResult, ProviderEvent, ProviderSession } from "@acme/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import { DEFAULT_RUNTIME_MODE, type Project, type RuntimeMode, type Thread } from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "SET_RUNTIME_ERROR"; error: string | null }
| { type: "BOOTSTRAP_FROM_SERVER"; bootstrap: AppBootstrapResult };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
runtimeError: string | null;
}
const PERSISTED_STATE_KEY = "codething:renderer-state:v4";
const LEGACY_PERSISTED_STATE_KEYS = [
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
const initialState: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
runtimeError: null,
};
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const [legacyV3Key, legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
const rawLegacyV3 = window.localStorage.getItem(legacyV3Key);
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
const raw = rawCurrent ?? rawLegacyV3 ?? rawLegacyV2 ?? rawLegacyV1;
if (!raw) return initialState;
const hydrated = hydratePersistedState(
raw,
!rawCurrent && !rawLegacyV3 && !rawLegacyV2 && Boolean(rawLegacyV1),
);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false, runtimeError: null };
} catch {
return initialState;
}
}
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
function updateThread(
threads: Thread[],
threadId: string,
updater: (t: Thread) => Thread,
): Thread[] {
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
function getEventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.id);
}
function getEventThreadId(event: ProviderEvent): string | undefined {
if (event.threadId) return event.threadId;
const payload = asObject(event.payload);
return asString(payload?.threadId) ?? asString(asObject(payload?.thread)?.id);
}
function durationMs(startIso: string, endIso: string): number | undefined {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
return undefined;
}
return end - start;
}
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
latestTurnStartedAt: event.createdAt,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
};
}
if (event.method === "turn/completed") {
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
const startedAt =
completedTurnId && completedTurnId === thread.latestTurnId
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
latestTurnCompletedAt: event.createdAt,
latestTurnDurationMs: elapsed,
};
}
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "ADD_PROJECT":
return {
...state,
projects: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
},
],
};
case "TOGGLE_PROJECT":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "ADD_THREAD":
return {
...state,
threads: [
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
},
],
activeThreadId: action.thread.id,
};
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
return {
...state,
threads: updateThread(state.threads, target.id, (t) => ({
...t,
...(() => {
const eventThreadId = getEventThreadId(event);
const hasThreadMismatch =
t.codexThreadId !== null &&
eventThreadId !== undefined &&
eventThreadId !== t.codexThreadId;
const threadMismatchError = hasThreadMismatch
? `Thread identity mismatch: expected ${t.codexThreadId}, received ${eventThreadId}.`
: null;
return {
codexThreadId: t.codexThreadId ?? eventThreadId ?? null,
error:
threadMismatchError ??
(event.kind === "error" && event.message ? event.message : t.error),
};
})(),
session: t.session ? evolveSession(t.session, event) : t.session,
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
events: [event, ...t.events],
...updateTurnFields(t, event),
})),
};
}
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
codexThreadId: action.session.threadId ?? t.codexThreadId,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
id: action.id,
role: "user" as const,
text: action.text,
createdAt: new Date().toISOString(),
streaming: false,
},
],
})),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
case "SET_RUNTIME_ERROR":
return {
...state,
runtimeError: action.error,
};
case "BOOTSTRAP_FROM_SERVER": {
const { bootstrap } = action;
const existingProject = state.projects.find((project) => project.cwd === bootstrap.launchCwd);
const projectId = existingProject?.id ?? crypto.randomUUID();
const project =
existingProject ??
({
id: projectId,
name: bootstrap.projectName,
cwd: bootstrap.launchCwd,
model: resolveModelSlug(bootstrap.model),
expanded: true,
} satisfies Project);
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
const existingThread =
state.threads.find((thread) => thread.session?.sessionId === bootstrap.session.sessionId) ??
projectThreads.find(
(thread) =>
bootstrap.session.threadId !== undefined &&
thread.codexThreadId === bootstrap.session.threadId,
) ??
projectThreads[0];
const activeThreadId = existingThread?.id ?? crypto.randomUUID();
const thread =
existingThread ??
({
id: activeThreadId,
codexThreadId: bootstrap.session.threadId ?? null,
projectId,
title: "New thread",
model: resolveModelSlug(bootstrap.model),
session: bootstrap.session,
messages: [],
events: [],
error: bootstrap.bootstrapError ?? null,
createdAt: new Date().toISOString(),
} satisfies Thread);
return {
...state,
projects: existingProject
? state.projects.map((entry) =>
entry.id === existingProject.id
? {
...entry,
model: resolveModelSlug(bootstrap.model),
}
: entry,
)
: [project, ...state.projects],
threads: state.threads
.map((entry) =>
entry.id === thread.id
? {
...entry,
session: bootstrap.session,
codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId,
error: bootstrap.bootstrapError ?? entry.error,
}
: entry,
)
.concat(existingThread ? [] : [thread]),
activeThreadId,
runtimeError: null,
};
}
default:
return state;
}
}
// ── Context ──────────────────────────────────────────────────────────
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
}
+38
View File
@@ -0,0 +1,38 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
createdAt: string;
streaming: boolean;
}
export interface Project {
id: string;
name: string;
cwd: string;
model: string;
expanded: boolean;
}
export interface Thread {
id: string;
codexThreadId: string | null;
projectId: string;
title: string;
model: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
import type { NativeApi } from "@acme/contracts";
declare global {
interface Window {
nativeApi?: NativeApi;
}
}
File diff suppressed because it is too large. Load diff
+525
View File
@@ -0,0 +1,525 @@
import type {
AgentExit,
NativeApi,
OutputChunk,
ProviderEvent,
WsNativeApiMethod,
WsClientMessage,
WsEventMessage,
WsResponseMessage,
} from "@acme/contracts";
import {
WS_CLOSE_CODES,
WS_CLOSE_REASONS,
WS_EVENT_CHANNELS,
agentSessionIdSchema,
appBootstrapResultSchema,
appHealthResultSchema,
dialogsPickFolderResultSchema,
providerSessionListSchema,
providerSessionSchema,
providerTurnStartResultSchema,
terminalCommandResultSchema,
todoListSchema,
wsServerMessageSchema,
} from "@acme/contracts";
type PendingRequest = {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
timeout: ReturnType<typeof setTimeout>;
};
type SubscriptionSet<TValue> = Set<(value: TValue) => void>;
type SafeParseResult<TValue> = { success: true; data: TValue } | { success: false };
type SchemaLike<TValue> = {
safeParse: (value: unknown) => SafeParseResult<TValue>;
};
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_NESTED_ERROR_EXTRACTION_DEPTH = 8;
const textDecoder = new TextDecoder();
function closeDetailsFromEvent(event: unknown) {
const code = (event as { code?: unknown } | null)?.code;
const reason = (event as { reason?: unknown } | null)?.reason;
return {
code: normalizeCloseCode(code),
reason: normalizeNonEmptyString(reason),
};
}
function runtimeConnectErrorFromClose(event: unknown) {
const { code, reason } = closeDetailsFromEvent(event);
if (code === WS_CLOSE_CODES.unauthorized || reason === WS_CLOSE_REASONS.unauthorized) {
return new Error("Failed to connect to local t3 runtime: unauthorized websocket connection.");
}
if (
code === WS_CLOSE_CODES.replacedByNewClient ||
reason === WS_CLOSE_REASONS.replacedByNewClient
) {
return new Error(
"Failed to connect to local t3 runtime: replaced by a newer websocket client.",
);
}
if (code === null && (!reason || reason.length === 0)) {
return new Error("Failed to connect to local t3 runtime.");
}
if (code === null) {
return new Error(`Failed to connect to local t3 runtime (close reason: ${reason}).`);
}
if (!reason || reason.length === 0) {
return new Error(`Failed to connect to local t3 runtime (close code ${code}).`);
}
return new Error(`Failed to connect to local t3 runtime (close code ${code}: ${reason}).`);
}
function requestDisconnectError(id: string, event: unknown) {
const { code, reason } = closeDetailsFromEvent(event);
if (code === WS_CLOSE_CODES.unauthorized || reason === WS_CLOSE_REASONS.unauthorized) {
return new Error(`Request ${id} failed: websocket disconnected (unauthorized).`);
}
if (
code === WS_CLOSE_CODES.replacedByNewClient ||
reason === WS_CLOSE_REASONS.replacedByNewClient
) {
return new Error(`Request ${id} failed: websocket disconnected (replaced-by-new-client).`);
}
if (code === null && (!reason || reason.length === 0)) {
return new Error(`Request ${id} failed: websocket disconnected.`);
}
if (code === null) {
return new Error(`Request ${id} failed: websocket disconnected (reason: ${reason}).`);
}
if (!reason || reason.length === 0) {
return new Error(`Request ${id} failed: websocket disconnected (code ${code}).`);
}
return new Error(`Request ${id} failed: websocket disconnected (code ${code}: ${reason}).`);
}
function requestSocketError(id: string, event: unknown) {
const message = socketErrorMessage(event);
if (typeof message === "string" && message.length > 0) {
return new Error(`Request ${id} failed: websocket errored (${message}).`);
}
return new Error(`Request ${id} failed: websocket errored.`);
}
function runtimeConnectErrorFromSocketError(event: unknown) {
const message = socketErrorMessage(event);
if (typeof message === "string" && message.length > 0) {
return new Error(`Failed to connect to local t3 runtime: websocket error (${message}).`);
}
return new Error("Failed to connect to local t3 runtime.");
}
function runtimeConnectErrorFromConstructionError(error: unknown) {
const message = messageFromUnknown(error);
if (message) {
return new Error(`Failed to connect to local t3 runtime: websocket error (${message}).`);
}
return new Error("Failed to connect to local t3 runtime.");
}
function socketErrorMessage(event: unknown) {
return messageFromUnknown(event);
}
function messageFromUnknown(value: unknown, depth = 0): string | null {
if (depth > MAX_NESTED_ERROR_EXTRACTION_DEPTH) {
return null;
}
const direct = normalizeNonEmptyString(value);
if (direct) {
return direct;
}
const message = normalizeNonEmptyString((value as { message?: unknown } | null)?.message);
if (message) {
return message;
}
const nestedErrorMessage = messageFromUnknown(
(value as { error?: unknown } | null)?.error,
depth + 1,
);
if (nestedErrorMessage) {
return nestedErrorMessage;
}
return messageFromUnknown((value as { cause?: unknown } | null)?.cause, depth + 1);
}
function normalizeNonEmptyString(value: unknown) {
if (typeof value !== "string") {
return null;
}
const normalized = value.trim();
if (normalized.length === 0) {
return null;
}
return normalized;
}
function normalizeCloseCode(value: unknown) {
if (typeof value !== "number" || !Number.isInteger(value)) {
return null;
}
return value;
}
class WsNativeApiClient {
private socket: WebSocket | null = null;
private connectPromise: Promise<WebSocket> | null = null;
private nextRequestId = 1;
private pending = new Map<string, PendingRequest>();
private providerEventListeners: SubscriptionSet<ProviderEvent> = new Set();
private agentOutputListeners: SubscriptionSet<OutputChunk> = new Set();
private agentExitListeners: SubscriptionSet<AgentExit> = new Set();
constructor(private readonly wsUrl: string) {}
private rejectPendingRequests(errorForRequest: (id: string) => Error) {
for (const [id, pending] of this.pending.entries()) {
clearTimeout(pending.timeout);
pending.reject(errorForRequest(id));
}
this.pending.clear();
}
private connect() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
return Promise.resolve(this.socket);
}
if (this.connectPromise) {
return this.connectPromise;
}
const connectAttempt = new Promise<WebSocket>((resolve, reject) => {
let socket: WebSocket;
try {
socket = new WebSocket(this.wsUrl);
} catch (error) {
reject(runtimeConnectErrorFromConstructionError(error));
return;
}
socket.binaryType = "arraybuffer";
this.socket = socket;
let hasOpened = false;
let connectionSettled = false;
const rejectConnection = (error?: Error) => {
if (connectionSettled) {
return;
}
connectionSettled = true;
this.connectPromise = null;
reject(error ?? new Error("Failed to connect to local t3 runtime."));
};
const resolveConnection = () => {
if (connectionSettled) {
return;
}
connectionSettled = true;
this.connectPromise = null;
resolve(socket);
};
socket.addEventListener("open", () => {
hasOpened = true;
resolveConnection();
});
socket.addEventListener("error", (event) => {
if (this.socket !== socket) {
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromSocketError(event));
}
return;
}
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromSocketError(event));
return;
}
this.socket = null;
this.rejectPendingRequests((id) => requestSocketError(id, event));
try {
socket.close();
} catch {
// best-effort close after error
}
});
socket.addEventListener("message", (event) => {
if (this.socket !== socket) {
return;
}
void this.handleMessage(event.data);
});
socket.addEventListener("close", (event) => {
if (this.socket !== socket) {
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromClose(event));
}
return;
}
this.socket = null;
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromClose(event));
return;
}
this.rejectPendingRequests((id) => requestDisconnectError(id, event));
});
});
this.connectPromise = connectAttempt;
connectAttempt.catch(() => {
if (this.connectPromise === connectAttempt) {
this.connectPromise = null;
}
});
return connectAttempt;
}
private async request(method: WsNativeApiMethod, params?: unknown) {
const socket = await this.connect();
const id = String(this.nextRequestId);
this.nextRequestId += 1;
const requestMessage: WsClientMessage = {
type: "request",
id,
method,
params,
};
const requestPromise = new Promise<unknown>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Request timed out for method '${method}'.`));
}, REQUEST_TIMEOUT_MS);
this.pending.set(id, { resolve, reject, timeout });
});
try {
socket.send(JSON.stringify(requestMessage));
} catch (error) {
const pending = this.pending.get(id);
if (pending) {
clearTimeout(pending.timeout);
this.pending.delete(id);
const sendErrorMessage = messageFromUnknown(error);
pending.reject(
new Error(
`Failed to send runtime request '${method}': ${sendErrorMessage ?? "unknown websocket failure"}`,
),
);
}
this.rejectPendingRequests((requestId) => requestSocketError(requestId, error));
if (this.socket === socket) {
this.socket = null;
}
try {
socket.close();
} catch {
// best-effort close after send failure
}
}
return requestPromise;
}
private async requestParsed<TValue>(
method: WsNativeApiMethod,
schema: SchemaLike<TValue>,
params?: unknown,
): Promise<TValue> {
const value = await this.request(method, params);
const parsed = schema.safeParse(value);
if (!parsed.success) {
throw new Error(`Runtime method '${method}' returned invalid response payload.`);
}
return parsed.data;
}
private async requestNullResult(method: WsNativeApiMethod, params?: unknown): Promise<void> {
const value = await this.request(method, params);
if (value !== null) {
throw new Error(`Runtime method '${method}' returned invalid response payload.`);
}
}
private handleResponse(message: WsResponseMessage) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
clearTimeout(pending.timeout);
if (message.ok) {
pending.resolve(message.result);
return;
}
pending.reject(new Error(message.error?.message ?? "Unknown runtime request failure."));
}
private handleEvent(message: WsEventMessage) {
if (message.channel === WS_EVENT_CHANNELS.providerEvent) {
for (const listener of this.providerEventListeners) {
listener(message.payload as ProviderEvent);
}
return;
}
if (message.channel === WS_EVENT_CHANNELS.agentOutput) {
for (const listener of this.agentOutputListeners) {
listener(message.payload as OutputChunk);
}
return;
}
if (message.channel === WS_EVENT_CHANNELS.agentExit) {
for (const listener of this.agentExitListeners) {
listener(message.payload as AgentExit);
}
}
}
private async decodeIncomingMessage(raw: unknown): Promise<string | null> {
if (typeof raw === "string") {
return raw;
}
if (ArrayBuffer.isView(raw)) {
return textDecoder.decode(raw);
}
if (raw instanceof ArrayBuffer) {
return textDecoder.decode(raw);
}
if (raw instanceof Blob) {
return raw.text();
}
return null;
}
private async handleMessage(raw: unknown) {
let decoded: string | null;
try {
decoded = await this.decodeIncomingMessage(raw);
} catch {
return;
}
if (!decoded) {
return;
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(decoded);
} catch {
return;
}
const parsed = wsServerMessageSchema.safeParse(parsedRaw);
if (!parsed.success) {
return;
}
if (parsed.data.type === "response") {
this.handleResponse(parsed.data);
return;
}
if (parsed.data.type === "event") {
this.handleEvent(parsed.data);
}
}
asNativeApi(): NativeApi {
return {
app: {
bootstrap: async () => this.requestParsed("app.bootstrap", appBootstrapResultSchema),
health: async () => this.requestParsed("app.health", appHealthResultSchema),
},
todos: {
list: async () => this.requestParsed("todos.list", todoListSchema),
add: async (input) => this.requestParsed("todos.add", todoListSchema, input),
toggle: async (id) => this.requestParsed("todos.toggle", todoListSchema, id),
remove: async (id) => this.requestParsed("todos.remove", todoListSchema, id),
},
dialogs: {
pickFolder: async () =>
this.requestParsed("dialogs.pickFolder", dialogsPickFolderResultSchema),
},
terminal: {
run: async (input) => this.requestParsed("terminal.run", terminalCommandResultSchema, input),
},
agent: {
spawn: async (config) => this.requestParsed("agent.spawn", agentSessionIdSchema, config),
kill: async (sessionId) => this.requestNullResult("agent.kill", sessionId),
write: async (sessionId, data) => this.requestNullResult("agent.write", { sessionId, data }),
onOutput: (callback) => {
this.agentOutputListeners.add(callback);
return () => {
this.agentOutputListeners.delete(callback);
};
},
onExit: (callback) => {
this.agentExitListeners.add(callback);
return () => {
this.agentExitListeners.delete(callback);
};
},
},
providers: {
startSession: async (input) =>
this.requestParsed("providers.startSession", providerSessionSchema, input),
sendTurn: async (input) =>
this.requestParsed("providers.sendTurn", providerTurnStartResultSchema, input),
interruptTurn: async (input) => this.requestNullResult("providers.interruptTurn", input),
respondToRequest: async (input) => this.requestNullResult("providers.respondToRequest", input),
stopSession: async (input) => this.requestNullResult("providers.stopSession", input),
listSessions: async () =>
this.requestParsed("providers.listSessions", providerSessionListSchema),
onEvent: (callback) => {
this.providerEventListeners.add(callback);
return () => {
this.providerEventListeners.delete(callback);
};
},
},
shell: {
openInEditor: async (cwd, editor) => this.requestNullResult("shell.openInEditor", { cwd, editor }),
},
};
}
}
function resolveWsUrl() {
const params = new URLSearchParams(window.location.search);
return params.get("ws") ?? "ws://127.0.0.1:4317";
}
let cachedApi: NativeApi | undefined;
export function getOrCreateWsNativeApi() {
if (cachedApi) {
return cachedApi;
}
cachedApi = new WsNativeApiClient(resolveWsUrl()).asNativeApi();
return cachedApi;
}
@@ -4,10 +4,7 @@
"composite": true,
"jsx": "react-jsx",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["vite/client"],
"paths": {
"~/*": ["./src/*"]
}
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}
+22
View File
@@ -0,0 +1,22 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
},
}),
tailwindcss(),
],
server: {
port: Number(process.env.T3_WEB_PORT ?? 5173),
strictPort: true,
},
build: {
outDir: "dist",
emptyOutDir: true,
},
});
-32
View File
@@ -1,32 +0,0 @@
{
"name": "t3",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
"files": [
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.mjs",
"start": "node dist/index.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
-21
View File
@@ -1,21 +0,0 @@
/**
* Copies the built web app into dist/client/ so the published npm package
* includes the web UI. This runs as a post-build step.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const webDist = path.resolve(__dirname, "../../web/dist");
const target = path.resolve(__dirname, "../dist/client");
if (!fs.existsSync(webDist)) {
console.log(
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
);
process.exit(0);
}
fs.cpSync(webDist, target, { recursive: true });
console.log("✓ Bundled web app into dist/client");
@@ -1,352 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
},
});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
);
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
});
it("ignores non-error structured codex logs", () => {
const line =
"2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("ignores known benign rollout path errors", () => {
const line =
"\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("keeps unknown structured errors", () => {
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
it("keeps plain stderr messages", () => {
const line = "fatal: permission denied";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("prefers codex id when model differs", () => {
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
});
it("keeps non-aliased models as-is", () => {
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches not-found resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
).toBe(true);
});
it("ignores non-resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
).toBe(false);
});
it("ignores non-recoverable resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/resume failed: timed out waiting for server"),
),
).toBe(false);
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
kind: event.kind,
...(event.message ? { message: event.message } : {}),
});
});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
provider: "codex",
}),
).rejects.toThrow("cwd missing");
expect(events).toHaveLength(1);
expect(events[0]).toEqual({
method: "session/startFailed",
kind: "error",
message: "cwd missing",
});
} finally {
processCwd.mockRestore();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: "sess_1",
input: "Inspect this image",
attachments: [
{
type: "image",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3",
effort: "high",
});
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
});
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Inspect this image",
text_elements: [],
},
{
type: "image",
url: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3-codex",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
});
});
it("supports image-only turns", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
},
],
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "image",
url: "data:image/png;base64,BBBB",
},
],
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
await expect(
manager.sendTurn({
sessionId: "sess_1",
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
});
describe("thread checkpoint control", () => {
it("reads thread turns from thread/read", async () => {
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
},
});
const result = await manager.readThread("sess_1");
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("reads thread turns from flat thread/read responses", async () => {
const { manager, context, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
const result = await manager.readThread("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("rolls back turns via thread/rollback and resets session running state", async () => {
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [],
},
});
const result = await manager.rollbackThread("sess_1", 2);
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
threadId: "thread_1",
numTurns: 2,
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "ready",
activeTurnId: undefined,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [],
});
});
});
-252
View File
@@ -1,252 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
CommitMessageGenerationInput,
CommitMessageGenerationResult,
PrContentGenerationInput,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const COMMIT_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
subject: { type: "string" },
body: { type: "string" },
},
required: ["subject", "body"],
additionalProperties: false,
} as const;
const PR_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
},
required: ["title", "body"],
additionalProperties: false,
} as const;
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object commit message payload.");
}
const record = raw as Record<string, unknown>;
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
const body = typeof record.body === "string" ? record.body : "";
if (subject.length === 0) {
throw new Error("Codex returned an empty commit subject.");
}
return { subject, body };
}
function parsePrOutput(raw: unknown): { title: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object PR payload.");
}
const record = raw as Record<string, unknown>;
const title = typeof record.title === "string" ? record.title.trim() : "";
const body = typeof record.body === "string" ? record.body.trim() : "";
if (title.length === 0 || body.length === 0) {
throw new Error("Codex returned an invalid PR title/body payload.");
}
return { title, body };
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
async function writeTempFile(prefix: string, content: string): Promise<string> {
const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
await fs.writeFile(filePath, content, "utf8");
return filePath;
}
async function safeUnlink(filePath: string): Promise<void> {
try {
await fs.unlink(filePath);
} catch {
// Best-effort cleanup.
}
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
async function runCodexJson<T>({
cwd,
prompt,
outputSchemaJson,
parse,
run,
}: {
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
run: ProcessRunner;
}): Promise<T> {
const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
let outputPath: string | null = null;
try {
outputPath = await writeTempFile("codex-output", "");
await run(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
timeoutMs: 180_000,
stdin: prompt,
},
);
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
if (rawOutput.length === 0) {
throw new Error("Codex returned an empty response.");
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(rawOutput);
} catch {
throw new Error("Codex returned invalid JSON output.");
}
return parse(parsedJson);
} finally {
await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
}
}
interface CodexTextGeneratorDeps {
runProcess?: ProcessRunner;
}
export class CodexTextGenerator implements TextGenerationService {
private readonly run: ProcessRunner;
constructor(deps: CodexTextGeneratorDeps = {}) {
this.run = deps.runProcess ?? runProcess;
}
async generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult> {
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
run: this.run,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
};
}
async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
run: this.run,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
}
}
-32
View File
@@ -1,32 +0,0 @@
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
}
export interface PrContentGenerationInput {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface PrContentGenerationResult {
title: string;
body: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}
@@ -1,243 +0,0 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
import { runProcess } from "./processRunner";
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
const result = await runProcess("git", args, {
cwd,
allowNonZeroExit: true,
});
if (result.code !== 0) {
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
}
return result.stdout.trim();
}
function exists(filePath: string): boolean {
return fs.existsSync(filePath);
}
async function createRepo(): Promise<string> {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
await runGit(cwd, ["init", "--initial-branch=main"]);
await runGit(cwd, ["config", "user.email", "[email protected]"]);
await runGit(cwd, ["config", "user.name", "Test User"]);
await writeFile(path.join(cwd, "README.md"), "v1\n");
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
await runGit(cwd, ["add", "."]);
await runGit(cwd, ["commit", "-m", "Initial"]);
return cwd;
}
async function createRepoWithoutHead(): Promise<string> {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
await runGit(cwd, ["init", "--initial-branch=main"]);
return cwd;
}
describe("FilesystemCheckpointStore", () => {
it("captures refs without mutating branch history and restores workspace state", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_1";
try {
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
const rootRef = checkpointRefForThreadTurn(threadId, 0);
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
expect(rootCommit.length).toBeGreaterThan(0);
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
await writeFile(path.join(cwd, "README.md"), "v2\n");
await rm(path.join(cwd, "tracked.txt"));
await writeFile(path.join(cwd, "notes.md"), "notes\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "v3\n");
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
expect(restoredRoot).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
expect(restoredTurn1).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns false when restoring a missing checkpoint", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
try {
const restored = await store.restoreCheckpoint({
cwd,
threadId: "thr_2",
turnCount: 999,
});
expect(restored).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_2b";
try {
await writeFile(path.join(cwd, "README.md"), "v2\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "v3\n");
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
const restored = await store.restoreCheckpoint({
cwd,
threadId,
turnCount: 0,
});
expect(restored).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("prunes refs newer than the retained turn", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_3";
try {
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "turn1\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "turn2\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
await store.pruneAfterTurn({
cwd,
threadId,
maxTurnCount: 1,
});
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns a unified patch between checkpoint turns", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_4";
try {
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "v2\n");
await writeFile(path.join(cwd, "new.txt"), "new file\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
const diff = await store.diffCheckpoints({
cwd,
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
expect(diff).toContain("diff --git a/README.md b/README.md");
expect(diff).toContain("diff --git a/new.txt b/new.txt");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_5";
try {
await writeFile(path.join(cwd, "README.md"), "v2\n");
await writeFile(path.join(cwd, "new.txt"), "new file\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
const diff = await store.diffCheckpoints({
cwd,
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
expect(diff).toContain("diff --git a/README.md b/README.md");
expect(diff).toContain("diff --git a/new.txt b/new.txt");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("detects non-repo folders", async () => {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
const store = new FilesystemCheckpointStore();
try {
expect(await store.isGitRepository(cwd)).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns false when repository path does not exist", async () => {
const store = new FilesystemCheckpointStore();
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
expect(await store.isGitRepository(cwd)).toBe(false);
});
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
const cwd = await createRepoWithoutHead();
const store = new FilesystemCheckpointStore();
const threadId = "thr-no-head";
try {
await writeFile(path.join(cwd, "README.md"), "first\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "second\n");
const restored = await store.restoreCheckpoint({
cwd,
threadId,
turnCount: 0,
});
expect(restored).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
});
@@ -1,322 +0,0 @@
import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { runProcess } from "./processRunner";
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function checkpointRefThreadSegment(threadId: string): string {
return Buffer.from(threadId, "utf8").toString("base64url");
}
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
if (!Number.isInteger(turnCount) || turnCount < 0) {
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
}
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
}
interface GitOptions {
env?: NodeJS.ProcessEnv;
stdin?: string;
allowNonZeroExit?: boolean;
}
export class FilesystemCheckpointStore {
async isGitRepository(cwd: string): Promise<boolean> {
try {
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
allowNonZeroExit: true,
});
return result.code === 0 && result.stdout.trim() === "true";
} catch {
return false;
}
}
async captureCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<void> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
try {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const hasHead = await this.hasHeadCommit(cwd);
if (hasHead) {
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
}
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
const treeOid = writeTreeResult.stdout.trim();
if (!treeOid) {
throw new Error("git write-tree returned an empty tree oid.");
}
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
env: commitEnv,
stdin: `${message}\n`,
});
const commitOid = commitTreeResult.stdout.trim();
if (!commitOid) {
throw new Error("git commit-tree returned an empty commit oid.");
}
await this.runGit(cwd, ["update-ref", ref, commitOid]);
} finally {
await rm(tempDir, { recursive: true, force: true });
}
}
async hasCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<boolean> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
const commit = await this.resolveCheckpointCommit(cwd, ref);
return commit !== null;
}
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
const { cwd, threadId } = input;
const rootRef = checkpointRefForThreadTurn(threadId, 0);
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
if (existing) {
return true;
}
const headCommit = await this.resolveHeadCommit(cwd);
if (!headCommit) {
return false;
}
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
return true;
}
async restoreCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<boolean> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
if (!commitOid && turnCount === 0) {
commitOid = await this.resolveHeadCommit(cwd);
}
if (!commitOid) {
return false;
}
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
if (await this.hasHeadCommit(cwd)) {
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
}
return true;
}
async diffCheckpoints(input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}): Promise<string> {
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
}
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
throw new Error(`Invalid to turn count: ${toTurnCount}`);
}
if (fromTurnCount > toTurnCount) {
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
}
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
if (!fromCommitOid && fromTurnCount === 0) {
const headCommit = await this.resolveHeadCommit(cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
);
}
if (!toCommitOid) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
);
}
const result = await this.runGit(cwd, [
"diff",
"--patch",
"--minimal",
"--no-color",
fromCommitOid,
toCommitOid,
]);
return result.stdout;
}
private async resolveHeadCommit(cwd: string): Promise<string | null> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
allowNonZeroExit: true,
});
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}
async pruneAfterTurn(input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}): Promise<void> {
const { cwd, threadId, maxTurnCount } = input;
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
}
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
const result = await this.runGit(
cwd,
["for-each-ref", "--format=%(refname)", threadRefPrefix],
{
allowNonZeroExit: true,
},
);
if (result.code !== 0) {
return;
}
const refsToDelete = result.stdout
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.filter((refName) => {
const turn = this.readRefTurnCount(refName);
return turn !== null && turn > maxTurnCount;
});
const batchSize = 32;
const batches = Array.from(
{ length: Math.ceil(refsToDelete.length / batchSize) },
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
);
await batches.reduce<Promise<void>>((pending, batch) => {
return pending.then(async () => {
await Promise.all(
batch.map((refName) =>
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
),
);
});
}, Promise.resolve());
}
private async hasHeadCommit(cwd: string): Promise<boolean> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
allowNonZeroExit: true,
});
return result.code === 0;
}
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
allowNonZeroExit: true,
});
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}
private readRefTurnCount(ref: string): number | null {
const segments = ref.split("/");
const rawTurn = segments.at(-1);
if (!rawTurn) {
return null;
}
const turn = Number.parseInt(rawTurn, 10);
return Number.isInteger(turn) && turn >= 0 ? turn : null;
}
private async runGit(
cwd: string,
args: readonly string[],
options: GitOptions = {},
): Promise<Awaited<ReturnType<typeof runProcess>>> {
let result: Awaited<ReturnType<typeof runProcess>>;
try {
result = await runProcess("git", args, {
cwd,
env: options.env,
stdin: options.stdin,
timeoutMs: DEFAULT_TIMEOUT_MS,
allowNonZeroExit: true,
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
}
if (result.timedOut) {
throw new Error(`${quoteGitCommand(args)} timed out.`);
}
if (result.stdoutTruncated || result.stderrTruncated) {
throw new Error(
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
);
}
if (!options.allowNonZeroExit && result.code !== 0) {
const stderr = result.stderr.trim();
throw new Error(
stderr.length > 0
? `${quoteGitCommand(args)} failed: ${stderr}`
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
);
}
return result;
}
}
-18
View File
@@ -1,18 +0,0 @@
import { execFileSync } from "node:child_process";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
if (result) {
process.env.PATH = result;
}
} catch {
// Silently ignore — keep default PATH
}
}
-904
View File
@@ -1,904 +0,0 @@
import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import {
GitCoreService,
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
// ── Helpers ──
/** Run a raw git command for test setup (not under test). */
async function git(cwd: string, command: string): Promise<string> {
const result = await runTerminalCommand({
command: `git ${command}`,
cwd,
timeoutMs: 10_000,
});
if (result.code !== 0) {
throw new Error(`git ${command} failed: ${result.stderr}`);
}
return result.stdout.trim();
}
/** Create a disposable temp directory that cleans up automatically. */
async function makeTmpDir() {
const dir = await mkdtemp(path.join(tmpdir(), "git-test-"));
return {
path: dir,
[Symbol.asyncDispose]: async () => {
await rm(dir, { recursive: true, force: true });
},
};
}
/** Create a repo with an initial commit so branches work. */
async function initRepoWithCommit(cwd: string): Promise<void> {
await initGitRepo({ cwd });
await git(cwd, "config user.email '[email protected]'");
await git(cwd, "config user.name 'Test'");
await writeFile(path.join(cwd, "README.md"), "# test\n");
await git(cwd, "add .");
await git(cwd, "commit -m 'initial commit'");
}
async function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Promise<void> {
await writeFile(path.join(cwd, fileName), fileContents);
await git(cwd, `add ${fileName}`);
const commitResult = await runTerminalCommand({
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
cwd,
timeoutMs: 10_000,
});
if (commitResult.code !== 0) {
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
}
}
// ── Tests ──
describe("git integration", () => {
describe("runTerminalCommand", () => {
it("caps captured output when maxOutputBytes is exceeded", async () => {
const result = await runTerminalCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
cwd: process.cwd(),
timeoutMs: 10_000,
maxOutputBytes: 128,
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stderr).toContain("output truncated");
});
});
// ── initGitRepo ──
describe("initGitRepo", () => {
it("creates a valid git repo", async () => {
await using tmp = await makeTmpDir();
await initGitRepo({ cwd: tmp.path });
expect(existsSync(path.join(tmp.path, ".git"))).toBe(true);
});
it("listGitBranches reports isRepo: true after init + commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
});
});
// ── listGitBranches ──
describe("listGitBranches", () => {
it("returns isRepo: false for non-git directory", async () => {
await using tmp = await makeTmpDir();
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(false);
expect(result.branches).toEqual([]);
});
it("returns the current branch with current: true", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current).toBeDefined();
expect(current!.current).toBe(true);
});
it("keeps current branch first and sorts the remaining branches by recency", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
await commitWithDate(
tmp.path,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
});
it("keeps default branch right after current branch", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(tmp.path, `push -u origin ${defaultBranch}`);
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
await commitWithDate(
tmp.path,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
});
it("lists multiple branches after creating them", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-a" });
await createGitBranch({ cwd: tmp.path, branch: "feature-b" });
const result = await listGitBranches({ cwd: tmp.path });
const names = result.branches.map((b) => b.name);
expect(names).toContain("feature-a");
expect(names).toContain("feature-b");
});
it("isDefault is false when no remote exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
});
});
// ── checkoutGitBranch ──
describe("checkoutGitBranch", () => {
it("checks out an existing branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature");
});
it("refreshes upstream behind count after checkout when remote branch advanced", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature-behind";
await createGitBranch({ cwd: source.path, branch: featureBranch });
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await checkoutGitBranch({ cwd: source.path, branch: defaultBranch });
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await git(clone.path, `checkout -b ${featureBranch} --track origin/${featureBranch}`);
await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n");
await git(clone.path, "add feature.txt");
await git(clone.path, "commit -m 'remote feature update'");
await git(clone.path, `push origin ${featureBranch}`);
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
const core = new GitCoreService();
await vi.waitFor(async () => {
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
});
});
it("keeps checkout successful when upstream refresh fails", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature-refresh-failure";
await git(source.path, `branch ${featureBranch}`);
await git(source.path, `checkout ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class RefreshFailingGitCoreService extends GitCoreService {
refreshFetchAttempts = 0;
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.refreshFetchAttempts += 1;
throw new Error("simulated fetch timeout");
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new RefreshFailingGitCoreService();
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
await vi.waitFor(() => {
expect(core.refreshFetchAttempts).toBe(1);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
});
it("refresh fetch is scoped to the checked out branch upstream refspec", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature/scoped-fetch";
await git(source.path, `checkout -b ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class FetchRecordingGitCoreService extends GitCoreService {
fetchArgs: readonly string[] | null = null;
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.fetchArgs = args;
return;
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new FetchRecordingGitCoreService();
await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
await vi.waitFor(() => {
expect(core.fetchArgs).not.toBeNull();
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
expect(core.fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
});
it("returns checkout result before background upstream refresh completes", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${defaultBranch}`);
const featureBranch = "feature/background-refresh";
await git(source.path, `checkout -b ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class SlowRefreshGitCoreService extends GitCoreService {
fetchStarted = false;
private readonly waitForReleasePromise: Promise<void>;
private releaseWait: () => void = () => undefined;
constructor() {
super();
this.waitForReleasePromise = new Promise<void>((resolve) => {
this.releaseWait = resolve;
});
}
releaseFetch(): void {
this.releaseWait();
}
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.fetchStarted = true;
await this.waitForReleasePromise;
return;
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new SlowRefreshGitCoreService();
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
await vi.waitFor(() => {
expect(core.fetchStarted).toBe(true);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
core.releaseFetch();
});
it("throws when branch does not exist", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow();
});
it("throws when checkout would overwrite uncommitted changes", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "other" });
// Create a conflicting change: modify README on current branch
await writeFile(path.join(tmp.path, "README.md"), "modified\n");
await git(tmp.path, "add README.md");
// First, checkout other branch cleanly
await git(tmp.path, "stash");
await checkoutGitBranch({ cwd: tmp.path, branch: "other" });
await writeFile(path.join(tmp.path, "README.md"), "other content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'other change'");
// Go back to default branch
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => !b.current,
)!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
// Make uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n");
// Checkout should fail due to uncommitted changes
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow();
});
});
// ── createGitBranch ──
describe("createGitBranch", () => {
it("creates a new branch visible in listGitBranches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "new-feature" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
});
it("throws when branch already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "dupe" });
await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow();
});
});
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
it("creates a worktree with a new branch from the base branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "worktree-out");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-branch",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("wt-branch");
expect(existsSync(wtPath)).toBe(true);
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
// Clean up worktree before tmp dir disposal
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("worktree has the new branch checked out", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-check-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-check",
path: wtPath,
});
// Verify the worktree is on the new branch
const branchOutput = await git(wtPath, "branch --show-current");
expect(branchOutput).toBe("wt-check");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("throws when new branch name already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "existing" });
const wtPath = path.join(tmp.path, "wt-conflict");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await expect(
createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "existing",
path: wtPath,
}),
).rejects.toThrow();
});
it("listGitBranches from worktree cwd reports worktree branch as current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-list-dir");
const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: mainBranch,
newBranch: "wt-list",
path: wtPath,
});
// listGitBranches from the worktree should show wt-list as current
const wtBranches = await listGitBranches({ cwd: wtPath });
expect(wtBranches.isRepo).toBe(true);
const wtCurrent = wtBranches.branches.find((b) => b.current);
expect(wtCurrent!.name).toBe("wt-list");
// Main repo should still show the original branch as current
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(mainBranch);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("removeGitWorktree cleans up the worktree", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-remove-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-remove",
path: wtPath,
});
expect(existsSync(wtPath)).toBe(true);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
expect(existsSync(wtPath)).toBe(false);
});
});
// ── Full flow: local branch checkout ──
describe("full flow: local branch checkout", () => {
it("init → commit → create branch → checkout → verify current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-login" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature-login");
});
});
// ── Full flow: worktree creation from base branch ──
describe("full flow: worktree creation", () => {
it("creates worktree with new branch from current branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const wtPath = path.join(tmp.path, "my-worktree");
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "feature-wt",
path: wtPath,
});
// Worktree exists
expect(existsSync(result.worktree.path)).toBe(true);
// Main repo still on original branch
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(currentBranch);
// Worktree is on the new branch
const wtBranch = await git(wtPath, "branch --show-current");
expect(wtBranch).toBe("feature-wt");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
});
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
it("checkout a → checkout b → checkout a → current matches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "branch-a" });
await createGitBranch({ cwd: tmp.path, branch: "branch-b" });
// Simulate switching to thread A's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
let branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
// Simulate switching to thread B's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
// Switch back to thread A
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
});
});
// ── Full flow: checkout conflict ──
describe("full flow: checkout conflict", () => {
it("uncommitted changes prevent checkout to a diverged branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "diverged" });
// Make diverged branch have different file content
await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" });
await writeFile(path.join(tmp.path, "README.md"), "diverged content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'diverge'");
// Actually, let's just get back to the initial branch explicitly
const allBranches = await listGitBranches({ cwd: tmp.path });
const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
// Make local uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n");
// Attempt checkout should fail
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow();
// Current branch should still be the initial one
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
});
});
describe("GitCoreService", () => {
it("supports branch lifecycle operations through the service API", async () => {
await using tmp = await makeTmpDir();
const core = new GitCoreService();
await core.initRepo({ cwd: tmp.path });
await git(tmp.path, "config user.email '[email protected]'");
await git(tmp.path, "config user.name 'Test'");
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'initial commit'");
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
const branches = await core.listBranches({ cwd: tmp.path });
expect(branches.isRepo).toBe(true);
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
});
it("reports status details and dirty state", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const clean = await core.status({ cwd: tmp.path });
expect(clean.hasWorkingTreeChanges).toBe(false);
expect(clean.branch).toBeTruthy();
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
const dirty = await core.statusDetails(tmp.path);
expect(dirty.hasWorkingTreeChanges).toBe(true);
});
it("includes command context when worktree removal fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const missingWorktreePath = path.join(tmp.path, "missing-worktree");
const error = await core
.removeWorktree({ cwd: tmp.path, path: missingWorktreePath })
.then(() => null)
.catch((err: unknown) => err);
expect(error).toBeInstanceOf(Error);
const message = (error as Error).message;
expect(message).toContain("git worktree remove");
expect(message).toContain(`cwd: ${tmp.path}`);
expect(message).toContain(missingWorktreePath);
});
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);
const core = new GitCoreService();
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(initialBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
});
it("prepares commit context by auto-staging and creates commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
it("pushes with upstream setup and then skips when up to date", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
const core = new GitCoreService();
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
await core.commit(tmp.path, "Add feature file", "");
const pushed = await core.pushCurrentBranch(tmp.path, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
"origin/feature/core-push",
);
const skipped = await core.pushCurrentBranch(tmp.path, null);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email '[email protected]'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);
const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);
const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});
it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const recencySpy = vi
.spyOn(core as any, "readBranchRecency")
.mockRejectedValueOnce(new Error("timeout"));
const result = await core.listBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches[0]?.current).toBe(true);
recencySpy.mockRestore();
});
});
});
-736
View File
@@ -1,736 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
type GitCreateBranchInput,
type GitCreateWorktreeInput,
type GitCreateWorktreeResult,
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import { type ProcessRunResult, runProcess } from "./processRunner";
export interface TerminalCommandInput {
command: string;
cwd: string;
timeoutMs?: number;
maxOutputBytes?: number;
}
export type TerminalCommandResult = ProcessRunResult;
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
interface RunGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
}
interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
}
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
/** Spawn git directly with an argv array — no shell, no quoting needed. */
function runGit(
args: readonly string[],
cwd: string,
timeoutMs = 30_000,
): Promise<ProcessRunResult> {
return runProcess("git", args, {
cwd,
timeoutMs,
allowNonZeroExit: true,
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
});
}
function trimStdout(value: string): string {
return value.trim();
}
function parseBranchAb(value: string): { ahead: number; behind: number } {
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
if (!match) return { ahead: 0, behind: 0 };
return {
ahead: Number(match[1] ?? "0"),
behind: Number(match[2] ?? "0"),
};
}
function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}
function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}
if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}
const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}
const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function normalizeGitSpawnError(cwd: string, error: unknown): Error {
if (!(error instanceof Error)) {
return new Error("Failed to run git command.");
}
if (!fs.existsSync(cwd)) {
return new Error(`Working directory does not exist: ${cwd}`);
}
if (error.message.includes("Command not found: git")) {
return new Error("Git is required but not available on PATH.");
}
return new Error(`Failed to run git command: ${error.message}`);
}
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return new Error("Current folder is not a git repository.");
}
if (result.timedOut) {
return new Error(`${commandLabel(args)} timed out.`);
}
const detail =
stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
return new Error(`${commandLabel(args)} failed: ${detail}`);
}
async function runGitOrThrow(
cwd: string,
args: readonly string[],
options: RunGitOptions = {},
): Promise<TerminalCommandResult> {
let result: TerminalCommandResult;
try {
result = await runGit(args, cwd, options.timeoutMs);
} catch (error) {
throw normalizeGitSpawnError(cwd, error);
}
if (result.timedOut) {
throw normalizeGitExecutionError(args, result);
}
if (!options.allowNonZeroExit && result.code !== 0) {
throw normalizeGitExecutionError(args, result);
}
return result;
}
async function executeGit(
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Promise<TerminalCommandResult> {
const result = await runGitOrThrow(cwd, args, {
timeoutMs: options.timeoutMs,
allowNonZeroExit: true,
});
if (options.allowNonZeroExit || result.code === 0) {
return result;
}
const stderr = result.stderr.trim();
if (stderr.length > 0) {
throw new Error(stderr);
}
if (options.fallbackErrorMessage) {
throw new Error(options.fallbackErrorMessage);
}
throw normalizeGitExecutionError(args, result);
}
export class GitCoreService {
private readonly lastUpstreamRefreshAt = new Map<string, number>();
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.statusDetails(input.cwd);
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
});
}
async statusDetails(cwd: string): Promise<GitStatusDetails> {
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
continue;
}
if (line.startsWith("# branch.upstream ")) {
const value = line.slice("# branch.upstream ".length).trim();
upstreamRef = value.length > 0 ? value : null;
continue;
}
if (line.startsWith("# branch.ab ")) {
const value = line.slice("# branch.ab ".length).trim();
const parsed = parseBranchAb(value);
aheadCount = parsed.ahead;
behindCount = parsed.behind;
continue;
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}
let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));
for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));
return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
};
}
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
return {
stagedSummary,
stagedPatch,
};
}
async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
const args = ["commit", "-m", subject];
const trimmedBody = body.trim();
if (trimmedBody.length > 0) {
args.push("-m", trimmedBody);
}
await this.git(cwd, args);
const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
return { commitSha };
}
async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
await this.git(cwd, ["push", "-u", "origin", branch]);
return {
status: "pushed",
branch,
upstreamBranch: `origin/${branch}`,
setUpstream: true,
};
}
await this.git(cwd, ["push"]);
return {
status: "pushed",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
setUpstream: false,
};
}
async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
this.gitStdout(cwd, ["log", "--oneline", range]),
this.gitStdout(cwd, ["diff", "--stat", range]),
this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
]);
return {
commitSummary,
diffSummary,
diffPatch,
};
}
async readConfigValue(cwd: string, key: string): Promise<string | null> {
const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
const value = trimStdout(stdout);
return value.length > 0 ? value : null;
}
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
const branchRecency = await executeGit(
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
},
);
const branchLastCommit = new Map<string, number>();
if (branchRecency.code !== 0) {
return branchLastCommit;
}
for (const line of branchRecency.stdout.split("\n")) {
if (line.length === 0) {
continue;
}
const [name, lastCommitRaw] = line.split("\t");
if (!name) {
continue;
}
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
}
return branchLastCommit;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
});
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
throw new Error(stderr || "git branch failed");
}
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
branchRecencyPromise,
]);
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
const worktreeMap = new Map<string, string>();
if (worktreeList.code === 0) {
let currentPath: string | null = null;
for (const line of worktreeList.stdout.split("\n")) {
if (line.startsWith("worktree ")) {
const candidatePath = line.slice("worktree ".length);
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
} else if (line.startsWith("branch refs/heads/") && currentPath) {
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
} else if (line === "") {
currentPath = null;
}
}
}
const branches = result.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
if (aPriority !== bPriority) return aPriority - bPriority;
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
});
return { branches, isRepo: true };
}
async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const worktreePath =
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
await executeGit(
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{ fallbackErrorMessage: "git worktree add failed" },
);
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
}
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
const args = ["worktree", "remove", input.path] as const;
try {
await executeGit(input.cwd, args, {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`${commandLabel(args)} failed (cwd: ${input.cwd}): ${detail}`, {
cause: error,
});
}
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
await executeGit(input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
}
private async resolveCurrentUpstream(
cwd: string,
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
const upstreamRef = trimStdout(
await this.gitStdout(
cwd,
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
true,
),
);
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
return null;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0) {
return null;
}
if (upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
}
private async fetchUpstreamRef(
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Promise<void> {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
}
private async fetchUpstreamRefForStatus(
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Promise<void> {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
allowNonZeroExit: true,
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
});
}
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
const upstream = await this.resolveCurrentUpstream(cwd);
if (!upstream) {
return;
}
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
const now = Date.now();
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
return;
}
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
this.lastUpstreamRefreshAt.set(cacheKey, now);
await this.fetchUpstreamRefForStatus(cwd, upstream);
}
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
const upstream = await this.resolveCurrentUpstream(cwd);
if (!upstream) {
return;
}
await this.fetchUpstreamRef(cwd, upstream);
}
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
await executeGit(input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
}
async initRepo(input: GitInitInput): Promise<void> {
await executeGit(input.cwd, ["init"], {
timeoutMs: 10_000,
fallbackErrorMessage: "git init failed",
});
}
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
await executeGit(cwd, args, { allowNonZeroExit });
}
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
const result = await executeGit(cwd, args, { allowNonZeroExit });
return result.stdout;
}
}
const defaultGitCoreService = new GitCoreService();
export async function runTerminalCommand(
input: TerminalCommandInput,
): Promise<TerminalCommandResult> {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
const result = await runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: maxOutputBytes,
outputMode: "truncate",
});
if (!result.stdoutTruncated && !result.stderrTruncated) {
return result;
}
return {
...result,
stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
};
}
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
return defaultGitCoreService.listBranches(input);
}
export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}
export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
return defaultGitCoreService.createWorktree(input);
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await defaultGitCoreService.removeWorktree(input);
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
await defaultGitCoreService.createBranch(input);
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
await defaultGitCoreService.checkoutBranch(input);
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
await defaultGitCoreService.initRepo(input);
}
-482
View File
@@ -1,482 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { GitManager } from "./gitManager";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
failWith?: Error;
}
interface FakeGitTextGenerator {
generateCommitMessage: (input: {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Promise<{ subject: string; body: string }>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Promise<{ title: string; body: string }>;
}
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function runGit(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<ProcessRunResult> {
return runProcess("git", args, { cwd, allowNonZeroExit });
}
async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await runGit(cwd, args);
return result.stdout.trim();
}
async function initRepo(cwd: string): Promise<void> {
await runGit(cwd, ["init", "--initial-branch=main"]);
await runGit(cwd, ["config", "user.email", "[email protected]"]);
await runGit(cwd, ["config", "user.name", "Test User"]);
fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
await runGit(cwd, ["add", "README.md"]);
await runGit(cwd, ["commit", "-m", "Initial commit"]);
}
async function createBareRemote(): Promise<string> {
const remoteDir = makeTempDir("t3code-git-remote-");
await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
return remoteDir;
}
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
body: "",
}),
generatePrContent: async () => ({
title: "Add stacked git actions",
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
}),
...overrides,
};
}
function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
runner: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
ghCalls: string[];
} {
const prListQueue = [...(scenario.prListSequence ?? [])];
const ghCalls: string[] = [];
const runner = async (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
): Promise<ProcessRunResult> => {
if (command !== "gh") {
return runProcess(command, args, options);
}
ghCalls.push(args.join(" "));
if (scenario.failWith) {
throw scenario.failWith;
}
if (args[0] === "pr" && args[1] === "list") {
const stdout = (prListQueue.shift() ?? "[]") + "\n";
return {
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "view") {
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "repo" && args[1] === "view") {
return {
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
throw new Error(`Unexpected gh command: ${args.join(" ")}`);
};
return { runner, ghCalls };
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("GitManager", () => {
it("status includes open PR metadata when branch already has an open PR", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
const { runner } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseRefName: "main",
headRefName: "feature/status-open-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-pr");
expect(status.openPr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
});
});
it("status is resilient to gh lookup failures and returns openPr null", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.openPr).toBeNull();
});
it("creates a commit when working tree is dirty", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"Implement stacked git actions",
);
});
it("uses custom commit message when provided", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
let generatedCount = 0;
const manager = new GitManager({
textGenerator: createTextGenerator({
generateCommitMessage: async () => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
};
},
}),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"feat: custom summary line",
);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
"- details from user",
);
});
it("skips commit when there are no uncommitted changes", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
});
it("commits and pushes with upstream auto-setup when needed", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/stacked-flow",
);
});
it("skips push when branch is already up to date", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
});
it("returns existing PR metadata for commit/push/pr action", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 42,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/existing-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
});
it("creates PR when one does not already exist", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
await runGit(repoDir, ["add", "changes.txt"]);
await runGit(repoDir, ["commit", "-m", "Feature commit"]);
await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
"[]",
JSON.stringify([
{
number: 88,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
baseRefName: "main",
headRefName: "feature-create-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
).toBe(true);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
});
it("rejects push/pr actions from detached HEAD", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
}),
).rejects.toThrow("detached HEAD");
});
it("surfaces missing gh binary errors", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("GitHub CLI (`gh`) is required");
});
it("surfaces gh auth errors with guidance", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("authentication failed"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("gh auth login");
});
});
-467
View File
@@ -1,467 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
gitRunStackedActionInputSchema,
gitRunStackedActionResultSchema,
gitStatusInputSchema,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import type {
CommitMessageGenerationResult,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { CodexTextGenerator } from "./codexTextGenerator";
import { GitCoreService } from "./git";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
const GH_CLI_TIMEOUT_MS = 30_000;
interface GitManagerDeps {
runProcess?: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
textGenerator?: TextGenerationService;
gitCore?: GitCoreService;
}
interface OpenPrInfo {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}
function parseOpenPrList(raw: unknown): OpenPrInfo[] {
if (!Array.isArray(raw)) return [];
const parsed: OpenPrInfo[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
continue;
}
if (
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
parsed.push({
number,
title,
url,
baseRefName,
headRefName,
});
}
return parsed;
}
function trimStdout(value: string): string {
return value.trim();
}
function limitContext(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(
generated: CommitMessageGenerationResult,
): CommitMessageGenerationResult {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
return {
subject: safeSubject,
body: generated.body.trim(),
};
}
function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
const normalized = raw.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
return null;
}
const [firstLine, ...rest] = normalized.split("\n");
const subject = firstLine?.trim() ?? "";
if (subject.length === 0) {
return null;
}
return {
subject,
body: rest.join("\n").trim(),
};
}
function extractBranchFromRef(ref: string): string {
const normalized = ref.trim();
if (normalized.startsWith("refs/remotes/")) {
const withoutPrefix = normalized.slice("refs/remotes/".length);
const firstSlash = withoutPrefix.indexOf("/");
if (firstSlash === -1) {
return withoutPrefix.trim();
}
return withoutPrefix.slice(firstSlash + 1).trim();
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
function asCommandNotFound(command: string, error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
if (command === "gh") {
return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
}
if (command === "codex") {
return new Error("Codex CLI (`codex`) is required but not available on PATH.");
}
return new Error(`${command} is required but not available on PATH.`);
}
function normalizeGitHubAuthError(error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
}
return undefined;
}
function toStatusOpenPr(pr: OpenPrInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
};
}
export class GitManager {
private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
private readonly textGenerator: TextGenerationService;
private readonly gitCore: GitCoreService;
constructor(deps: GitManagerDeps = {}) {
this.run = deps.runProcess ?? runProcess;
this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
this.gitCore = deps.gitCore ?? new GitCoreService();
}
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.gitCore.statusDetails(input.cwd);
let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
if (details.branch && details.hasUpstream) {
try {
const existing = await this.findOpenPr(input.cwd, details.branch);
if (existing) {
openPr = toStatusOpenPr(existing);
}
} catch {
// PR lookup is best-effort for status rendering.
}
}
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr,
};
}
async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
const input = gitRunStackedActionInputSchema.parse(raw);
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = await this.gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const push = wantsPush
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? await this.runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
return gitRunStackedActionResultSchema.parse({
action: input.action,
commit,
push,
pr,
});
}
private async runCommitStep(
cwd: string,
branch: string | null,
commitMessage?: string,
): Promise<{
status: "created" | "skipped_no_changes";
commitSha?: string | undefined;
subject?: string | undefined;
}> {
const context = await this.gitCore.prepareCommitContext(cwd);
if (!context) {
return { status: "skipped_no_changes" };
}
let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
commitMessage ?? "",
);
if (!generated) {
try {
generated = sanitizeCommitMessage(
await this.textGenerator.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
}),
);
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
}
const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
return {
status: "created",
commitSha,
subject: generated.subject,
};
}
private async runPrStep(
cwd: string,
fallbackBranch: string | null,
): Promise<{
status: "created" | "opened_existing" | "skipped_not_requested";
url?: string | undefined;
number?: number | undefined;
baseBranch?: string | undefined;
headBranch?: string | undefined;
title?: string | undefined;
}> {
const details = await this.gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has not been pushed. Push before creating a PR.");
}
const existing = await this.findOpenPr(cwd, branch);
if (existing) {
return {
status: "opened_existing",
url: existing.url,
number: existing.number,
baseBranch: existing.baseRefName,
headBranch: existing.headRefName,
title: existing.title,
};
}
const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
let generated: PrContentGenerationResult;
try {
generated = await this.textGenerator.generatePrContent({
cwd,
baseBranch,
headBranch: branch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
});
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
await fs.writeFile(bodyFile, generated.body, "utf8");
try {
await this.runGh(cwd, [
"pr",
"create",
"--base",
baseBranch,
"--head",
branch,
"--title",
generated.title,
"--body-file",
bodyFile,
]);
} finally {
try {
await fs.unlink(bodyFile);
} catch {
// Best-effort cleanup.
}
}
const created = await this.findOpenPr(cwd, branch);
if (!created) {
return {
status: "created",
baseBranch,
headBranch: branch,
title: generated.title,
};
}
return {
status: "created",
url: created.url,
number: created.number,
baseBranch: created.baseRefName,
headBranch: created.headRefName,
title: created.title,
};
}
private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [
"pr",
"list",
"--head",
branch,
"--state",
"open",
"--limit",
"1",
"--json",
"number,title,url,baseRefName,headRefName",
]);
const raw = trimStdout(stdout);
if (raw.length === 0) return null;
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
throw new Error("GitHub CLI returned invalid PR list JSON.");
}
const parsed = parseOpenPrList(parsedJson);
return parsed[0] ?? null;
}
private async resolveBaseBranch(
cwd: string,
branch: string,
upstreamRef: string | null,
): Promise<string> {
const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
}
}
try {
const ghDefault = await this.runGhStdout(cwd, [
"repo",
"view",
"--json",
"defaultBranchRef",
"--jq",
".defaultBranchRef.name",
]);
const defaultBranch = trimStdout(ghDefault);
if (defaultBranch.length > 0) return defaultBranch;
} catch {
// Fall through to deterministic fallback.
}
return "main";
}
private async runGh(cwd: string, args: readonly string[]): Promise<void> {
await this.runGhCommand(cwd, args);
}
private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await this.runGhCommand(cwd, args);
return result.stdout;
}
private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
try {
return await this.run("gh", args, {
cwd,
timeoutMs: GH_CLI_TIMEOUT_MS,
});
} catch (error) {
throw (
asCommandNotFound("gh", error) ??
normalizeGitHubAuthError(error) ??
(error instanceof Error ? error : new Error("GitHub CLI command failed."))
);
}
}
}
-176
View File
@@ -1,176 +0,0 @@
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { fixPath } from "./fixPath";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { createServer } from "./wsServer";
fixPath();
const DEFAULT_PORT = 3773;
const cwd = process.cwd();
const logger = createLogger("server");
type RuntimeMode = "web" | "desktop";
function parseBooleanEnv(value: string | undefined): boolean | undefined {
if (value === undefined) return undefined;
const normalized = value.trim().toLowerCase();
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off"].includes(normalized)) return false;
return undefined;
}
function parsePort(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
throw new Error(`Invalid T3CODE_PORT: ${value}`);
}
return parsed;
}
function expandHomePath(input: string): string {
if (input === "~") return os.homedir();
if (input.startsWith("~/")) {
return path.join(os.homedir(), input.slice(2));
}
return input;
}
function resolveStateDir(raw: string | undefined): string {
if (!raw || raw.trim().length === 0) {
return path.join(os.homedir(), ".t3", "userdata");
}
return path.resolve(expandHomePath(raw.trim()));
}
async function findAvailablePort(preferred: number): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.listen(preferred, () => {
server.close(() => resolve(preferred));
});
server.on("error", () => {
// Preferred port busy — let the OS pick one
const fallback = net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
fallback.close(() => {
if (port > 0) resolve(port);
else reject(new Error("Could not find an available port."));
});
});
fallback.on("error", reject);
});
});
}
function resolveStaticDir(): string | undefined {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Check for bundled client (npm publish / npx scenario):
// dist/client/ lives alongside dist/index.js
const bundledClient = path.resolve(__dirname, "client");
try {
const stat = fs.statSync(path.join(bundledClient, "index.html"));
if (stat.isFile()) return bundledClient;
} catch {
// Not bundled — check monorepo layout
}
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
const monorepoClient = path.resolve(__dirname, "../../web/dist");
try {
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
if (stat.isFile()) return monorepoClient;
} catch {
// Not found — probably dev mode, Vite will serve
}
return undefined;
}
async function main() {
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
const requestedPort = parsePort(process.env.T3CODE_PORT);
const port =
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const projectRegistry = new ProjectRegistry(stateDir);
const devUrl = process.env.VITE_DEV_SERVER_URL;
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
const authToken = process.env.T3CODE_AUTH_TOKEN;
const staticDir = devUrl ? undefined : resolveStaticDir();
if (!devUrl && !staticDir) {
logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
});
}
const server = createServer({
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
staticDir,
devUrl,
projectRegistry,
authToken,
});
await server.start();
const url = `http://localhost:${port}`;
logger.info("T3 Code running", {
url,
cwd,
mode,
stateDir,
authEnabled: Boolean(authToken),
});
// Open browser (dynamic import because `open` is ESM-only)
if (!noBrowser) {
try {
const open = await import("open");
const target = devUrl ?? url;
await open.default(target);
} catch {
logger.info("browser auto-open unavailable", {
hint: `Open ${devUrl ?? url} in your browser.`,
});
}
}
// Graceful shutdown
let shuttingDown = false;
async function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
logger.info("shutting down");
try {
await server.stop();
process.exit(0);
} catch (error) {
logger.error("failed to stop server cleanly", { error });
process.exit(1);
}
}
process.on("SIGINT", () => {
void shutdown();
});
process.on("SIGTERM", () => {
void shutdown();
});
}
main().catch((err) => {
logger.error("failed to start T3 Code", { error: err });
process.exit(1);
});
-225
View File
@@ -1,225 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, afterEach, describe, expect, it, vi } from "vitest";
import {
compileResolvedKeybindingRule,
parseKeybindingShortcut,
upsertKeybindingRule,
} from "./keybindings";
describe("server keybindings", () => {
const tempDirs: string[] = [];
const logger = {
warn: vi.fn(),
};
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
vi.restoreAllMocks();
logger.warn.mockReset();
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("parses shortcuts including plus key", () => {
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
assert.deepEqual(parseKeybindingShortcut("mod++"), {
key: "+",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
});
it("compiles valid rule with parsed when AST", () => {
const compiled = compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalOpen && !terminalFocus",
});
assert.deepEqual(compiled, {
command: "terminal.split",
shortcut: {
key: "d",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "and",
left: { type: "identifier", name: "terminalOpen" },
right: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
});
});
it("rejects invalid rules", () => {
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+shift+d+o",
command: "terminal.new",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
});
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
const resolved = upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persisted).toEqual([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
});
it("replaces existing custom keybinding for the same command", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
});
it("refuses to overwrite malformed keybindings config", () => {
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, "{ not-json", "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/Unable to parse keybindings config/);
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
});
it("reports non-array config parse errors without duplicate prefix", () => {
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).not.toThrow(
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
);
});
it("cleans up temp files when atomic keybinding write fails", () => {
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
vi.spyOn(fs, "renameSync").mockImplementation(() => {
throw new Error("rename failed");
});
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/rename failed/);
expect(fs.readFileSync(configPath, "utf8")).toBe(
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
);
const tempFiles = fs
.readdirSync(configDir)
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
expect(tempFiles).toEqual([]);
});
});
-447
View File
@@ -1,447 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
KeybindingRule,
KeybindingsConfig,
KeybindingShortcut,
KeybindingWhenNode,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { keybindingRuleSchema } from "@t3tools/contracts";
interface KeybindingsLogger {
warn(message: string, context?: Record<string, unknown>): void;
}
type WhenToken =
| { type: "identifier"; value: string }
| { type: "not" }
| { type: "and" }
| { type: "or" }
| { type: "lparen" }
| { type: "rparen" };
const MAX_WHEN_EXPRESSION_DEPTH = 256;
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
];
function normalizeKeyToken(token: string): string {
if (token === "space") return " ";
if (token === "esc") return "escape";
return token;
}
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
const rawTokens = value
.toLowerCase()
.split("+")
.map((token) => token.trim());
const tokens = [...rawTokens];
let trailingEmptyCount = 0;
while (tokens[tokens.length - 1] === "") {
trailingEmptyCount += 1;
tokens.pop();
}
if (trailingEmptyCount > 0) {
tokens.push("+");
}
if (tokens.some((token) => token.length === 0)) {
return null;
}
if (tokens.length === 0) return null;
let key: string | null = null;
let metaKey = false;
let ctrlKey = false;
let shiftKey = false;
let altKey = false;
let modKey = false;
for (const token of tokens) {
switch (token) {
case "cmd":
case "meta":
metaKey = true;
break;
case "ctrl":
case "control":
ctrlKey = true;
break;
case "shift":
shiftKey = true;
break;
case "alt":
case "option":
altKey = true;
break;
case "mod":
modKey = true;
break;
default: {
if (key !== null) return null;
key = normalizeKeyToken(token);
}
}
}
if (key === null) return null;
return {
key,
metaKey,
ctrlKey,
shiftKey,
altKey,
modKey,
};
}
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
const tokens: WhenToken[] = [];
let index = 0;
while (index < expression.length) {
const current = expression[index];
if (!current) break;
if (/\s/.test(current)) {
index += 1;
continue;
}
if (expression.startsWith("&&", index)) {
tokens.push({ type: "and" });
index += 2;
continue;
}
if (expression.startsWith("||", index)) {
tokens.push({ type: "or" });
index += 2;
continue;
}
if (current === "!") {
tokens.push({ type: "not" });
index += 1;
continue;
}
if (current === "(") {
tokens.push({ type: "lparen" });
index += 1;
continue;
}
if (current === ")") {
tokens.push({ type: "rparen" });
index += 1;
continue;
}
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
if (!identifier) {
return null;
}
tokens.push({ type: "identifier", value: identifier[0] });
index += identifier[0].length;
}
return tokens;
}
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
const token = tokens[index];
if (!token) return null;
if (token.type === "identifier") {
index += 1;
return { type: "identifier", name: token.value };
}
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr(depth + 1);
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
}
index += 1;
return expressionNode;
}
return null;
};
const parseUnary = (depth: number): KeybindingWhenNode | null => {
let notCount = 0;
while (tokens[index]?.type === "not") {
index += 1;
notCount += 1;
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
}
let node = parsePrimary(depth);
if (!node) return null;
while (notCount > 0) {
node = { type: "not", node };
notCount -= 1;
}
return node;
};
const parseAnd = (depth: number): KeybindingWhenNode | null => {
let left = parseUnary(depth);
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary(depth);
if (!right) return null;
left = { type: "and", left, right };
}
return left;
};
const parseOr = (depth: number): KeybindingWhenNode | null => {
let left = parseAnd(depth);
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd(depth);
if (!right) return null;
left = { type: "or", left, right };
}
return left;
};
const ast = parseOr(0);
if (!ast || index !== tokens.length) return null;
return ast;
}
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
const key = rule.key.trim();
if (key.length === 0) return null;
const shortcut = parseKeybindingShortcut(key);
if (!shortcut) return null;
const when = rule.when?.trim();
if (when && when.length > 0) {
const whenAst = parseKeybindingWhenExpression(when);
if (!whenAst) return null;
return {
command: rule.command,
shortcut,
whenAst,
};
}
return {
command: rule.command,
shortcut,
};
}
export function compileResolvedKeybindingsConfig(
config: KeybindingsConfig,
): ResolvedKeybindingsConfig {
const compiled: ResolvedKeybindingsConfig = [];
for (const rule of config) {
const resolved = compileResolvedKeybindingRule(rule);
if (!resolved) continue;
compiled.push(resolved);
}
return compiled;
}
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
const resolved: ResolvedKeybindingsConfig = [];
for (const rule of DEFAULT_KEYBINDINGS) {
const compiled = compileResolvedKeybindingRule(rule);
if (!compiled) {
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
}
resolved.push(compiled);
}
return resolved;
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
const MAX_KEYBINDINGS = 256;
class KeybindingsConfigParseError extends Error {
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
}
}
function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
function loadCustomKeybindingsConfig(
logger: KeybindingsLogger,
options?: {
throwOnUnreadableConfig?: boolean;
},
): KeybindingsConfig {
const configPath = resolveKeybindingsConfigPath();
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
if (options?.throwOnUnreadableConfig) {
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [];
}
const sanitized: KeybindingsConfig = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = keybindingRuleSchema.safeParse(entry);
if (result.success) {
if (!compileResolvedKeybindingRule(result.data)) {
invalidEntries += 1;
continue;
}
sanitized.push(result.data);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
return sanitized;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
if (options?.throwOnUnreadableConfig) {
if (error instanceof KeybindingsConfigParseError) {
throw error;
}
throw new KeybindingsConfigParseError(
configPath,
error instanceof Error ? error.message : String(error),
{ cause: error },
);
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
});
return [];
}
}
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
fs.renameSync(tempPath, configPath);
} catch (error) {
fs.rmSync(tempPath, { force: true });
throw error;
}
}
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
const overriddenCommands = new Set(custom.map((binding) => binding.command));
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
(binding) => !overriddenCommands.has(binding.command),
);
const merged = [...retainedDefaults, ...custom];
if (merged.length <= MAX_KEYBINDINGS) {
return merged;
}
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
return merged.slice(-MAX_KEYBINDINGS);
}
export function loadResolvedKeybindingsConfig(
logger: KeybindingsLogger,
): ResolvedKeybindingsConfig {
const customConfig = loadCustomKeybindingsConfig(logger);
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + compiledCustomConfig.length;
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
logger.warn("truncating merged keybindings config to max entries", {
path: resolveKeybindingsConfigPath(),
maxEntries: MAX_KEYBINDINGS,
});
}
return merged;
}
export function upsertKeybindingRule(
logger: KeybindingsLogger,
rawRule: unknown,
): ResolvedKeybindingsConfig {
const rule = keybindingRuleSchema.parse(rawRule);
if (!compileResolvedKeybindingRule(rule)) {
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
}
const configPath = resolveKeybindingsConfigPath();
const customConfig = loadCustomKeybindingsConfig(logger, {
throwOnUnreadableConfig: true,
});
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS) {
logger.warn("truncating keybindings config to max entries", {
path: configPath,
maxEntries: MAX_KEYBINDINGS,
});
}
fs.mkdirSync(path.dirname(configPath), { recursive: true });
writeConfigAtomically(configPath, cappedConfig);
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
return mergeWithDefaultKeybindings(compiledCustomConfig);
}
-103
View File
@@ -1,103 +0,0 @@
import util from "node:util";
type LogLevel = "info" | "warn" | "error" | "event";
type LogContext = Record<string, unknown>;
const ANSI = {
reset: "\u001b[0m",
dim: "\u001b[2m",
cyan: "\u001b[36m",
yellow: "\u001b[33m",
red: "\u001b[31m",
magenta: "\u001b[35m",
} as const;
const LEVEL_LABEL: Record<LogLevel, string> = {
info: "INFO",
warn: "WARN",
error: "ERROR",
event: "EVENT",
};
const LEVEL_COLOR: Record<LogLevel, string> = {
info: ANSI.cyan,
warn: ANSI.yellow,
error: ANSI.red,
event: ANSI.magenta,
};
function useColors() {
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
}
function colorize(value: string, color: string, enabled: boolean) {
return enabled ? `${color}${value}${ANSI.reset}` : value;
}
function timeStamp() {
return new Date().toISOString().slice(11, 23);
}
function formatValue(value: unknown) {
if (typeof value === "string") {
return JSON.stringify(value);
}
if (
typeof value === "number" ||
typeof value === "boolean" ||
value === null ||
value === undefined
) {
return String(value);
}
return util.inspect(value, {
depth: 4,
breakLength: Infinity,
compact: true,
maxArrayLength: 25,
maxStringLength: 320,
});
}
function formatContext(context: LogContext | undefined) {
if (!context) return "";
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
if (entries.length === 0) return "";
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
}
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
const colorEnabled = useColors();
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
const contextText = formatContext(context);
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
if (level === "warn") {
console.warn(line);
return;
}
if (level === "error") {
console.error(line);
return;
}
console.log(line);
}
export function createLogger(scope: string) {
return {
info(message: string, context?: LogContext) {
write("info", scope, message, context);
},
warn(message: string, context?: LogContext) {
write("warn", scope, message, context);
},
error(message: string, context?: LogContext) {
write("error", scope, message, context);
},
event(message: string, context?: LogContext) {
write("event", scope, message, context);
},
};
}
-23
View File
@@ -1,23 +0,0 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
).rejects.toThrow("exceeded stdout buffer limit");
});
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
maxBufferBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
});
-242
View File
@@ -1,242 +0,0 @@
import { spawn } from "node:child_process";
export interface ProcessRunOptions {
cwd?: string | undefined;
timeoutMs?: number | undefined;
env?: NodeJS.ProcessEnv | undefined;
stdin?: string | undefined;
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
}
export interface ProcessRunResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
stdoutTruncated?: boolean | undefined;
stderrTruncated?: boolean | undefined;
}
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
const maybeCode = (error as NodeJS.ErrnoException).code;
if (maybeCode === "ENOENT") {
return new Error(`Command not found: ${command}`);
}
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
const stderr = result.stderr.trim();
const detail = stderr.length > 0 ? ` ${stderr}` : "";
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
}
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
}
function normalizeBufferError(
command: string,
args: readonly string[],
stream: "stdout" | "stderr",
maxBufferBytes: number,
): Error {
return new Error(
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
);
}
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
export async function runProcess(
command: string,
args: readonly string[],
options: ProcessRunOptions = {},
): Promise<ProcessRunResult> {
const timeoutMs = options.timeoutMs ?? 60_000;
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const outputMode = options.outputMode ?? "error";
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
});
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let stdoutTruncated = false;
let stderrTruncated = false;
let timedOut = false;
let settled = false;
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
const timeoutTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
forceKillTimer = setTimeout(() => {
child.kill("SIGKILL");
}, 1_000);
}, timeoutMs);
const finalize = (callback: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timeoutTimer);
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
callback();
};
const fail = (error: Error): void => {
child.kill("SIGTERM");
finalize(() => {
reject(error);
});
};
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
return null;
}
stdout += text;
stdoutBytes += byteLength;
if (stdoutBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
return null;
}
stderr += text;
stderrBytes += byteLength;
if (stderrBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
}
}
return null;
};
child.stdout.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stdout", chunk);
if (error) {
fail(error);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stderr", chunk);
if (error) {
fail(error);
}
});
child.once("error", (error) => {
finalize(() => {
reject(normalizeSpawnError(command, args, error));
});
});
child.once("close", (code, signal) => {
const result: ProcessRunResult = {
stdout,
stderr,
code,
signal,
timedOut,
stdoutTruncated,
stderrTruncated,
};
finalize(() => {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
return;
}
resolve(result);
});
});
child.stdin.once("error", (error) => {
fail(normalizeStdinError(command, args, error));
});
if (options.stdin !== undefined) {
child.stdin.write(options.stdin, (error) => {
if (error) {
fail(normalizeStdinError(command, args, error));
return;
}
child.stdin.end();
});
return;
}
child.stdin.end();
});
}
-113
View File
@@ -1,113 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ProjectRegistry } from "./projectRegistry";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("ProjectRegistry scripts", () => {
it("stores and reloads project scripts", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "run",
name: "Run",
command: "bun run dev",
icon: "play",
runOnWorktreeCreate: false,
},
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[1]?.id).toBe("setup");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
const reloaded = new ProjectRegistry(stateDir);
const listed = reloaded.list();
expect(listed).toHaveLength(1);
expect(listed[0]?.scripts).toHaveLength(2);
expect(listed[0]?.scripts[0]?.id).toBe("run");
expect(listed[0]?.scripts[1]?.id).toBe("setup");
});
it("deduplicates script ids and allows only one setup script", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "setup",
name: "Setup",
command: "echo setup",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "setup",
name: "Setup Duplicate",
command: "echo duplicate",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "another",
name: "Another Setup",
command: "echo another",
icon: "play",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[0]?.id).toBe("setup");
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
expect(updated.project.scripts[1]?.id).toBe("another");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
});
it("throws when updating scripts for an unknown project id", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const registry = new ProjectRegistry(stateDir);
expect(() =>
registry.updateScripts({
id: "missing-project",
scripts: [],
}),
).toThrowError("Project not found");
});
});
-235
View File
@@ -1,235 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import {
type ProjectAddInput,
type ProjectAddResult,
type ProjectListResult,
type ProjectRecord,
type ProjectRemoveInput,
type ProjectScript,
type ProjectUpdateScriptsInput,
type ProjectUpdateScriptsResult,
normalizeProjectScripts,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
} from "@t3tools/contracts";
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
const cloned: ProjectScript[] = [];
for (const script of scripts) {
cloned.push({
id: script.id,
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
});
}
return cloned;
}
function normalizeCwd(rawCwd: string): string {
const resolved = path.resolve(rawCwd.trim());
const normalized = path.normalize(resolved);
if (process.platform === "win32") {
return normalized.toLowerCase();
}
return normalized;
}
function isDirectory(cwd: string): boolean {
try {
return fs.statSync(cwd).isDirectory();
} catch {
return false;
}
}
function inferProjectName(cwd: string): string {
const name = path.basename(cwd);
return name.length > 0 ? name : "project";
}
export class ProjectRegistry {
private readonly stateDir: string;
private readonly filePath: string;
private projects: ProjectRecord[];
constructor(stateDir: string) {
this.stateDir = stateDir;
this.filePath = path.join(this.stateDir, "projects.json");
fs.mkdirSync(this.stateDir, { recursive: true });
this.projects = this.loadFromDisk();
}
list(): ProjectListResult {
return this.projects.map((project) => ({
...project,
scripts: cloneScripts(project.scripts),
}));
}
add(raw: ProjectAddInput): ProjectAddResult {
const input = projectAddInputSchema.parse(raw);
const normalizedCwd = normalizeCwd(input.cwd);
if (!isDirectory(normalizedCwd)) {
throw new Error(`Project path does not exist: ${normalizedCwd}`);
}
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
if (existing) {
return {
project: {
...existing,
scripts: cloneScripts(existing.scripts),
},
created: false,
};
}
const now = new Date().toISOString();
const project: ProjectRecord = {
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
scripts: [],
createdAt: now,
updatedAt: now,
};
this.projects = [project, ...this.projects];
this.persist();
return {
project: {
...project,
scripts: cloneScripts(project.scripts),
},
created: true,
};
}
remove(raw: ProjectRemoveInput): void {
const input = projectRemoveInputSchema.parse(raw);
const next = this.projects.filter((project) => project.id !== input.id);
if (next.length === this.projects.length) {
return;
}
this.projects = next;
this.persist();
}
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
const input = projectUpdateScriptsInputSchema.parse(raw);
const index = this.projects.findIndex((project) => project.id === input.id);
if (index < 0) {
throw new Error(`Project not found: ${input.id}`);
}
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
const nextUpdatedAt = new Date().toISOString();
const nextProject: ProjectRecord = {
...this.projects[index]!,
scripts: nextScripts,
updatedAt: nextUpdatedAt,
};
const nextProjects = [...this.projects];
nextProjects[index] = nextProject;
this.projects = nextProjects;
this.persist();
return {
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
};
}
private loadFromDisk(): ProjectRecord[] {
const loaded = this.readPersistedProjects();
const deduped = new Map<string, ProjectRecord>();
const normalizedProjects: ProjectRecord[] = [];
for (const project of loaded) {
const normalizedCwd = normalizeCwd(project.cwd);
if (!isDirectory(normalizedCwd)) {
continue;
}
if (deduped.has(normalizedCwd)) {
continue;
}
const normalizedProject: ProjectRecord = {
...project,
cwd: normalizedCwd,
name:
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
scripts: normalizeProjectScripts(project.scripts),
};
deduped.set(normalizedCwd, normalizedProject);
normalizedProjects.push(normalizedProject);
}
const changed =
normalizedProjects.length !== loaded.length ||
normalizedProjects.some((project, index) => {
const source = loaded[index];
if (!source) return true;
return (
source.id !== project.id ||
source.cwd !== project.cwd ||
source.name !== project.name ||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
source.createdAt !== project.createdAt ||
source.updatedAt !== project.updatedAt
);
});
if (changed) {
this.projects = normalizedProjects;
this.persist();
}
return normalizedProjects;
}
private readPersistedProjects(): ProjectRecord[] {
try {
const raw = fs.readFileSync(this.filePath, "utf8");
const parsed = JSON.parse(raw) as { projects?: unknown };
if (!parsed || !Array.isArray(parsed.projects)) {
return [];
}
const projects: ProjectRecord[] = [];
for (const candidate of parsed.projects) {
const row = projectRecordSchema.safeParse(candidate);
if (!row.success) {
continue;
}
projects.push(row.data);
}
return projects;
} catch {
return [];
}
}
private persist(): void {
const payload = JSON.stringify(
{
version: 1,
projects: this.projects,
},
null,
2,
);
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
fs.writeFileSync(tempFile, payload);
fs.renameSync(tempFile, this.filePath);
}
}
-803
View File
@@ -1,803 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { ProviderManager } from "./providerManager";
describe("ProviderManager", () => {
it("detaches provider event listener and ends thread log streams on dispose", () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: { listenerCount: (event: string) => number };
onCodexEvent: (event: {
id: string;
kind: "notification";
provider: "codex";
sessionId: string;
createdAt: string;
method: string;
threadId: string;
}) => void;
threadLogStreams: Map<string, { writableEnded: boolean; destroyed: boolean }>;
};
internals.onCodexEvent({
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: new Date().toISOString(),
method: "thread/started",
threadId: "thread-1",
});
const stream = internals.threadLogStreams.get("thread-1");
expect(stream).toBeDefined();
if (!stream) return;
expect(internals.codex.listenerCount("event")).toBe(1);
manager.dispose();
expect(internals.codex.listenerCount("event")).toBe(0);
expect(stream.writableEnded || stream.destroyed).toBe(true);
expect(internals.threadLogStreams.size).toBe(0);
});
it("allows multiple dispose calls", () => {
const manager = new ProviderManager();
manager.dispose();
expect(() => manager.dispose()).not.toThrow();
});
it("rejects request responses for unknown sessions", async () => {
const manager = new ProviderManager();
await expect(
manager.respondToRequest({
sessionId: "missing-session",
requestId: "req-1",
decision: "accept",
}),
).rejects.toThrow("Unknown provider session: missing-session");
manager.dispose();
});
it("rejects checkpoint operations for unknown sessions", async () => {
const manager = new ProviderManager();
await expect(
manager.listCheckpoints({
sessionId: "missing-session",
}),
).rejects.toThrow("Unknown provider session: missing-session");
await expect(
manager.revertToCheckpoint({
sessionId: "missing-session",
turnCount: 0,
}),
).rejects.toThrow("Unknown provider session: missing-session");
await expect(
manager.getCheckpointDiff({
sessionId: "missing-session",
fromTurnCount: 0,
toTurnCount: 1,
}),
).rejects.toThrow("Unknown provider session: missing-session");
manager.dispose();
});
it("derives checkpoints from thread turns", async () => {
const manager = new ProviderManager();
const codex = (
manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
}
).codex;
codex.hasSession = () => true;
codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{
id: "turn_1",
items: [
{
type: "userMessage",
content: [{ type: "text", text: "Refactor the logger" }],
},
{
type: "agentMessage",
text: "I refactored it.",
},
],
},
],
});
const result = await manager.listCheckpoints({
sessionId: "sess_1",
});
expect(result).toEqual({
threadId: "thr_1",
checkpoints: [
{
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: false,
},
{
id: "turn_1",
turnCount: 1,
messageCount: 2,
label: "Turn 1",
preview: "Refactor the logger",
isCurrent: true,
},
],
});
manager.dispose();
});
it("rolls back from a selected checkpoint turn count", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
{ id: "turn_3", items: [] },
],
});
internals.codex.rollbackThread = async (sessionId, numTurns) => {
rollbackCalls.push({ sessionId, numTurns });
return {
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
};
};
const hasCheckpoint = vi.fn(async () => true);
const restoreCheckpoint = vi.fn(async () => true);
const pruneAfterTurn = vi.fn(async () => undefined);
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
});
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
expect(result.threadId).toBe("thr_1");
expect(result.turnCount).toBe(1);
expect(result.messageCount).toBe(0);
expect(result.rolledBackTurns).toBe(2);
expect(result.checkpoints).toHaveLength(2);
expect(hasCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 1,
});
manager.dispose();
});
it("returns diff text for a checkpoint range", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(result).toEqual({
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
diff: "diff --git a/a.ts b/a.ts",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
});
manager.dispose();
});
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
captureCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<void>;
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
cwd: "/repo",
},
];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
const isGitRepository = vi.fn(async () => true);
const ensureRootCheckpoint = vi.fn(async () => true);
const captureCheckpoint = vi.fn(async () => undefined);
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.delete("sess_1");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
expect(isGitRepository).toHaveBeenCalledWith("/repo");
expect(captureCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 2,
});
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/repo");
manager.dispose();
});
it("falls back to process cwd for lazy checkpoint init when session cwd is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
captureCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<void>;
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
try {
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
},
];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
});
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
const ensureRootCheckpoint = vi.fn(async () => true);
const captureCheckpoint = vi.fn(async () => undefined);
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.delete("sess_1");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 0,
toTurnCount: 1,
});
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
expect(isGitRepository).toHaveBeenCalledWith("/fallback-repo");
expect(captureCheckpoint).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
turnCount: 1,
});
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
fromTurnCount: 0,
toTurnCount: 1,
});
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/fallback-repo");
} finally {
processCwd.mockRestore();
manager.dispose();
}
});
it("does not fall back to process cwd when a session cwd exists but is not a git repo", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
try {
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
cwd: "/session-cwd",
},
];
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.sessionCheckpointCwds.delete("sess_1");
await expect(
manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 0,
toTurnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
expect(isGitRepository).toHaveBeenCalledWith("/session-cwd");
expect(isGitRepository).not.toHaveBeenCalledWith("/fallback-repo");
} finally {
processCwd.mockRestore();
manager.dispose();
}
});
it("fails revert when filesystem checkpoints are unavailable for the session", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
},
];
internals.filesystemCheckpointStore.isGitRepository = async () => false;
internals.sessionCheckpointCwds.delete("sess_1");
await expect(
manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
manager.dispose();
});
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
const callOrder: string[] = [];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = async () => {
callOrder.push("rollback");
return {
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
};
};
const hasCheckpoint = vi.fn(async () => true);
const restoreCheckpoint = vi.fn(async () => {
callOrder.push("restore");
return true;
});
const pruneAfterTurn = vi.fn(async () => {
callOrder.push("prune");
return undefined;
});
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
});
expect(result.turnCount).toBe(1);
expect(hasCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 1,
});
expect(callOrder).toEqual(["restore", "rollback", "prune"]);
manager.dispose();
});
it("reverts to turn 0 without requiring an explicit turn 0 checkpoint ref", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = async () => ({
threadId: "thr_1",
turns: [],
});
const hasCheckpoint = vi.fn(async () => false);
const restoreCheckpoint = vi.fn(async () => true);
const pruneAfterTurn = vi.fn(async () => undefined);
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 0,
});
expect(result.turnCount).toBe(0);
expect(hasCheckpoint).not.toHaveBeenCalled();
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 0,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 0,
});
manager.dispose();
});
it("fails before rollback when filesystem checkpoint is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
const rollbackSpy = vi.fn(async () => ({
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
}));
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = rollbackSpy;
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
await expect(
manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
expect(rollbackSpy).not.toHaveBeenCalled();
manager.dispose();
});
});
-617
View File
@@ -1,617 +0,0 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import {
type ProviderCheckpoint,
type ProviderEvent,
type ProviderGetCheckpointDiffInput,
type ProviderGetCheckpointDiffResult,
type ProviderInterruptTurnInput,
type ProviderListCheckpointsInput,
type ProviderListCheckpointsResult,
type ProviderRevertToCheckpointInput,
type ProviderRevertToCheckpointResult,
type ProviderRespondToRequestInput,
type ProviderSendTurnInput,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderStopSessionInput,
type ProviderTurnStartResult,
providerInterruptTurnInputSchema,
providerGetCheckpointDiffInputSchema,
providerListCheckpointsInputSchema,
providerRevertToCheckpointInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
import { CodexAppServerManager } from "./codexAppServerManager";
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
export interface ProviderManagerEvents {
event: [event: ProviderEvent];
}
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function trimToPreview(value: string): string {
const normalized = value.replace(/\s+/g, " ").trim();
if (normalized.length <= 120) {
return normalized;
}
return `${normalized.slice(0, 117)}...`;
}
function summarizeUserMessageContent(content: unknown[]): string | undefined {
const segments: string[] = [];
for (const part of content) {
const record = asObject(part);
const type = asString(record?.type);
if (!type) continue;
if (type === "text") {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
segments.push(text.trim());
}
continue;
}
if (type === "image") {
segments.push("[Image attachment]");
continue;
}
if (type === "localImage") {
segments.push("[Local image attachment]");
continue;
}
}
if (segments.length === 0) {
return undefined;
}
return trimToPreview(segments.join(" "));
}
function summarizeTurn(turn: CodexThreadTurnSnapshot): {
messageCountDelta: number;
preview?: string;
} {
let messageCountDelta = 0;
let preview: string | undefined;
for (const item of turn.items) {
const record = asObject(item);
const type = asString(record?.type);
if (!type) continue;
if (type === "userMessage") {
messageCountDelta += 1;
if (!preview) {
const content = asArray(record?.content);
preview = summarizeUserMessageContent(content);
}
continue;
}
if (type === "agentMessage") {
messageCountDelta += 1;
if (!preview) {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
preview = trimToPreview(text);
}
}
}
}
return {
messageCountDelta,
...(preview ? { preview } : {}),
};
}
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
const checkpoints: ProviderCheckpoint[] = [];
let messageCount = 0;
const isEmpty = turns.length === 0;
checkpoints.push({
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: isEmpty,
});
for (let index = 0; index < turns.length; index += 1) {
const turn = turns[index];
if (!turn) continue;
const turnSummary = summarizeTurn(turn);
messageCount += turnSummary.messageCountDelta;
checkpoints.push({
id: turn.id,
turnCount: index + 1,
messageCount,
label: `Turn ${index + 1}`,
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
isCurrent: index === turns.length - 1,
});
}
return checkpoints;
}
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private readonly codex = new CodexAppServerManager();
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
private readonly threadLogsDir: string;
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
private readonly sessionThreadIds = new Map<string, string>();
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
private readonly sessionCheckpointCwds = new Map<string, string>();
private readonly filesystemLocks = new Map<string, Promise<void>>();
private disposed = false;
private readonly onCodexEvent = (event: ProviderEvent) => {
if (this.disposed) {
return;
}
this.routeEventToThreadLog(event);
this.emit("event", event);
this.maybeCaptureFilesystemCheckpoint(event);
};
constructor() {
super();
const logsDir = path.resolve(process.cwd(), ".logs");
this.threadLogsDir = path.join(logsDir, "threads");
fs.mkdirSync(this.threadLogsDir, { recursive: true });
this.codex.on("event", this.onCodexEvent);
}
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
const input = providerSessionStartInputSchema.parse(raw);
if (input.provider !== "codex") {
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
}
const session = await this.codex.startSession(input);
if (session.threadId) {
this.sessionThreadIds.set(session.sessionId, session.threadId);
this.flushPendingSessionEvents(session.sessionId, session.threadId);
}
await this.initializeFilesystemCheckpointing(session, input.cwd).catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
});
return session;
}
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
const input = providerSendTurnInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
return this.codex.sendTurn(input);
}
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
const input = providerInterruptTurnInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.interruptTurn(input.sessionId, input.turnId);
}
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
const input = providerRespondToRequestInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);
}
stopSession(raw: ProviderStopSessionInput): void {
const input = providerStopSessionInputSchema.parse(raw);
this.codex.stopSession(input.sessionId);
this.sessionThreadIds.delete(input.sessionId);
this.pendingEventsBySession.delete(input.sessionId);
this.sessionCheckpointCwds.delete(input.sessionId);
this.filesystemLocks.delete(input.sessionId);
}
listSessions(): ProviderSession[] {
return this.codex.listSessions();
}
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
const input = providerListCheckpointsInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const snapshot = await this.codex.readThread(input.sessionId);
return {
threadId: snapshot.threadId,
checkpoints: buildCheckpoints(snapshot.turns),
};
}
async getCheckpointDiff(
raw: ProviderGetCheckpointDiffInput,
): Promise<ProviderGetCheckpointDiffResult> {
const input = providerGetCheckpointDiffInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const snapshot = await this.codex.readThread(input.sessionId);
if (input.toTurnCount > snapshot.turns.length) {
throw new Error(
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
);
}
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
cwd: checkpointCwd,
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
});
return {
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
});
}
async revertToCheckpoint(
raw: ProviderRevertToCheckpointInput,
): Promise<ProviderRevertToCheckpointResult> {
const input = providerRevertToCheckpointInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const beforeSnapshot = await this.codex.readThread(input.sessionId);
const currentTurnCount = beforeSnapshot.turns.length;
if (input.turnCount > currentTurnCount) {
throw new Error(
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
);
}
if (checkpointCwd && input.turnCount > 0) {
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!hasCheckpoint) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
}
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!restored) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
const requestedRollbackTurns = currentTurnCount - input.turnCount;
const afterSnapshot =
requestedRollbackTurns > 0
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
: beforeSnapshot;
await this.filesystemCheckpointStore.pruneAfterTurn({
cwd: checkpointCwd,
threadId: afterSnapshot.threadId,
maxTurnCount: afterSnapshot.turns.length,
});
const checkpoints = buildCheckpoints(afterSnapshot.turns);
const currentCheckpoint =
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
checkpoints[checkpoints.length - 1] ??
checkpoints[0];
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
return {
threadId: afterSnapshot.threadId,
turnCount: currentCheckpoint?.turnCount ?? 0,
messageCount: currentCheckpoint?.messageCount ?? 0,
rolledBackTurns,
checkpoints,
};
});
}
stopAll(): void {
this.codex.stopAll();
}
dispose(): void {
if (this.disposed) {
return;
}
this.disposed = true;
this.codex.off("event", this.onCodexEvent);
for (const stream of this.threadLogStreams.values()) {
stream.end();
}
this.threadLogStreams.clear();
this.sessionThreadIds.clear();
this.pendingEventsBySession.clear();
this.sessionCheckpointCwds.clear();
this.filesystemLocks.clear();
}
private async initializeFilesystemCheckpointing(
session: ProviderSession,
preferredCwd?: string,
): Promise<void> {
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
await this.withFilesystemLock(session.sessionId, async () => {
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
if (!supportsGit) {
this.sessionCheckpointCwds.delete(session.sessionId);
return;
}
const snapshot = await this.codex.readThread(session.sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
if (this.codex.hasSession(session.sessionId)) {
this.sessionCheckpointCwds.set(session.sessionId, cwd);
}
});
}
private async getOrInitializeFilesystemCheckpointCwd(sessionId: string): Promise<string | null> {
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
if (existingCwd) {
return existingCwd;
}
const session = this.codex
.listSessions()
.find((candidate) => candidate.sessionId === sessionId);
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
await this.withFilesystemLock(sessionId, async () => {
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
if (currentCwd) {
return;
}
const cwdSupport = await Promise.all(
candidateCwds.map(async (cwd) => ({
cwd,
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
})),
);
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
if (supportedCwd) {
const snapshot = await this.codex.readThread(sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
if (this.codex.hasSession(sessionId)) {
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
}
return;
}
this.sessionCheckpointCwds.delete(sessionId);
});
return this.sessionCheckpointCwds.get(sessionId) ?? null;
}
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
if (event.kind !== "notification" || event.method !== "turn/completed") {
return;
}
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
if (!checkpointCwd) {
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId).catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
return;
}
void this.withFilesystemLock(event.sessionId, async () => {
if (!this.codex.hasSession(event.sessionId)) {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: checkpointCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
}).catch((error) => {
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
}
private emitFilesystemCheckpointError(
sessionId: string,
message: string,
threadId?: string,
): void {
this.emit("event", {
id: randomUUID(),
kind: "error",
provider: "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "checkpoint/filesystemError",
message,
...(threadId ? { threadId } : {}),
});
}
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
const next = previous.catch(() => undefined).then(fn);
const completion = next.then(
() => undefined,
() => undefined,
);
this.filesystemLocks.set(sessionId, completion);
return next.finally(() => {
const tracked = this.filesystemLocks.get(sessionId);
if (tracked === completion) {
this.filesystemLocks.delete(sessionId);
}
});
}
private routeEventToThreadLog(event: ProviderEvent): void {
const threadId = this.resolveThreadId(event);
if (!threadId) {
const pending = this.pendingEventsBySession.get(event.sessionId) ?? [];
pending.push(event);
this.pendingEventsBySession.set(event.sessionId, pending.slice(-100));
return;
}
this.flushPendingSessionEvents(event.sessionId, threadId);
this.writeThreadEvent(threadId, event);
}
private flushPendingSessionEvents(sessionId: string, threadId: string): void {
const pending = this.pendingEventsBySession.get(sessionId);
if (!pending || pending.length === 0) {
return;
}
for (const event of pending) {
this.writeThreadEvent(threadId, event);
}
this.pendingEventsBySession.delete(sessionId);
}
private resolveThreadId(event: ProviderEvent): string | undefined {
const fromPayload = this.readThreadIdFromPayload(event.payload);
const threadId = event.threadId ?? fromPayload ?? this.sessionThreadIds.get(event.sessionId);
if (threadId) {
this.sessionThreadIds.set(event.sessionId, threadId);
}
return threadId;
}
private readThreadIdFromPayload(payload: unknown): string | undefined {
if (!payload || typeof payload !== "object") {
return undefined;
}
const record = payload as Record<string, unknown>;
const direct = record.threadId;
if (typeof direct === "string" && direct.length > 0) {
return direct;
}
const thread = record.thread;
if (!thread || typeof thread !== "object") {
return undefined;
}
const nested = (thread as Record<string, unknown>).id;
if (typeof nested === "string" && nested.length > 0) {
return nested;
}
return undefined;
}
private writeThreadEvent(threadId: string, event: ProviderEvent): void {
const stream = this.getOrCreateThreadLogStream(threadId);
stream.write(`${JSON.stringify(event)}\n`);
}
private getOrCreateThreadLogStream(threadId: string): fs.WriteStream {
const cached = this.threadLogStreams.get(threadId);
if (cached) {
return cached;
}
const safeThreadId = threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
const stream = fs.createWriteStream(
path.join(this.threadLogsDir, `${safeThreadId}.events.ndjson`),
{ flags: "a" },
);
this.threadLogStreams.set(threadId, stream);
return stream;
}
}
-54
View File
@@ -1,54 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ensureNodePtySpawnHelperExecutable } from "./ptyAdapter";
function fileMode(filePath: string): number {
return fs.statSync(filePath).mode & 0o777;
}
describe("ensureNodePtySpawnHelperExecutable", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("adds executable bits when helper exists but is not executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o644);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("keeps executable helper as executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o755);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("does not throw when helper path is missing", () => {
const missing = path.join(os.tmpdir(), `does-not-exist-${Date.now()}`);
expect(() => ensureNodePtySpawnHelperExecutable(missing)).not.toThrow();
});
});
-131
View File
@@ -1,131 +0,0 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import * as nodePty from "node-pty";
export interface PtyExitEvent {
exitCode: number;
signal: number | null;
}
export interface PtyProcess {
readonly pid: number;
write(data: string): void;
resize(cols: number, rows: number): void;
kill(signal?: string): void;
onData(callback: (data: string) => void): () => void;
onExit(callback: (event: PtyExitEvent) => void): () => void;
}
export interface PtySpawnInput {
shell: string;
args?: string[];
cwd: string;
cols: number;
rows: number;
env: NodeJS.ProcessEnv;
}
export interface PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess;
}
const requireForNodePty = createRequire(import.meta.url);
let didEnsureSpawnHelperExecutable = false;
function resolveNodePtySpawnHelperPath(): string | null {
try {
const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
const packageDir = path.dirname(packageJsonPath);
const candidates = [
path.join(packageDir, "build", "Release", "spawn-helper"),
path.join(packageDir, "build", "Debug", "spawn-helper"),
path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
} catch {
return null;
}
}
export function ensureNodePtySpawnHelperExecutable(explicitPath?: string): void {
if (process.platform === "win32") return;
if (!explicitPath && didEnsureSpawnHelperExecutable) return;
const helperPath = explicitPath ?? resolveNodePtySpawnHelperPath();
if (!helperPath) return;
if (!explicitPath) {
didEnsureSpawnHelperExecutable = true;
}
try {
const stat = fs.statSync(helperPath);
const mode = stat.mode & 0o777;
if ((mode & 0o111) === 0) {
fs.chmodSync(helperPath, mode | 0o111);
}
} catch {
// Best effort only. If chmod fails, node-pty spawn will surface the real error.
}
}
class NodePtyProcess implements PtyProcess {
constructor(private readonly process: nodePty.IPty) {}
get pid(): number {
return this.process.pid;
}
write(data: string): void {
this.process.write(data);
}
resize(cols: number, rows: number): void {
this.process.resize(cols, rows);
}
kill(signal?: string): void {
this.process.kill(signal);
}
onData(callback: (data: string) => void): () => void {
const disposable = this.process.onData(callback);
return () => {
disposable.dispose();
};
}
onExit(callback: (event: PtyExitEvent) => void): () => void {
const disposable = this.process.onExit((event) => {
callback({
exitCode: event.exitCode,
signal: event.signal ?? null,
});
});
return () => {
disposable.dispose();
};
}
}
export class NodePtyAdapter implements PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess {
ensureNodePtySpawnHelperExecutable();
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
cwd: input.cwd,
cols: input.cols,
rows: input.rows,
env: input.env,
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
});
return new NodePtyProcess(ptyProcess);
}
}
-566
View File
@@ -1,566 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type TerminalEvent,
type TerminalOpenInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
import { TerminalManager } from "./terminalManager";
class FakePtyProcess implements PtyProcess {
readonly writes: string[] = [];
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
private readonly dataListeners = new Set<(data: string) => void>();
private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();
killed = false;
constructor(readonly pid: number) {}
write(data: string): void {
this.writes.push(data);
}
resize(cols: number, rows: number): void {
this.resizeCalls.push({ cols, rows });
}
kill(): void {
this.killed = true;
}
onData(callback: (data: string) => void): () => void {
this.dataListeners.add(callback);
return () => {
this.dataListeners.delete(callback);
};
}
onExit(callback: (event: PtyExitEvent) => void): () => void {
this.exitListeners.add(callback);
return () => {
this.exitListeners.delete(callback);
};
}
emitData(data: string): void {
for (const listener of this.dataListeners) {
listener(data);
}
}
emitExit(event: PtyExitEvent): void {
for (const listener of this.exitListeners) {
listener(event);
}
}
}
class FakePtyAdapter implements PtyAdapter {
readonly spawnInputs: PtySpawnInput[] = [];
readonly processes: FakePtyProcess[] = [];
readonly spawnFailures: Error[] = [];
private nextPid = 9000;
spawn(input: PtySpawnInput): PtyProcess {
this.spawnInputs.push(input);
const failure = this.spawnFailures.shift();
if (failure) {
throw failure;
}
const process = new FakePtyProcess(this.nextPid++);
this.processes.push(process);
return process;
}
}
function waitFor(predicate: () => boolean, timeoutMs = 800): Promise<void> {
const started = Date.now();
return new Promise((resolve, reject) => {
const poll = () => {
if (predicate()) {
resolve();
return;
}
if (Date.now() - started > timeoutMs) {
reject(new Error("Timed out waiting for condition"));
return;
}
setTimeout(poll, 15);
};
poll();
});
}
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
return {
threadId: "thread-1",
cwd: process.cwd(),
cols: 100,
rows: 24,
...overrides,
};
}
function historyLogName(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
}
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return path.join(logsDir, historyLogName(threadId));
}
function multiTerminalHistoryLogPath(
logsDir: string,
threadId = "thread-1",
terminalId = "default",
): string {
return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
describe("TerminalManager", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
function makeManager(
historyLineLimit = 5,
options: {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
subprocessPollIntervalMs?: number;
} = {},
) {
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
tempDirs.push(logsDir);
const ptyAdapter = new FakePtyAdapter();
const manager = new TerminalManager({
logsDir,
ptyAdapter,
historyLineLimit,
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
});
return { logsDir, ptyAdapter, manager };
}
it("spawns lazily and reuses running terminal per thread", async () => {
const { manager, ptyAdapter } = makeManager();
const [first, second] = await Promise.all([
manager.open(openInput()),
manager.open(openInput()),
]);
const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1");
expect(first.terminalId).toBe("default");
expect(second.threadId).toBe("thread-1");
expect(third.threadId).toBe("thread-1");
expect(ptyAdapter.spawnInputs).toHaveLength(1);
manager.dispose();
});
it("forwards write and resize to active pty process", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
await manager.write({ threadId: "thread-1", data: "ls\n" });
await manager.resize({ threadId: "thread-1", cols: 120, rows: 30 });
expect(process.writes).toEqual(["ls\n"]);
expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]);
manager.dispose();
});
it("resizes running terminal on open when a different size is requested", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ cols: 100, rows: 24 }));
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
await manager.open(openInput({ cols: 140, rows: 40 }));
expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]);
manager.dispose();
});
it("preserves existing terminal size on open when size is omitted", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ cols: 100, rows: 24 }));
const ptyProcess = ptyAdapter.processes[0];
expect(ptyProcess).toBeDefined();
if (!ptyProcess) return;
await manager.open({
threadId: "thread-1",
cwd: globalThis.process.cwd(),
});
expect(ptyProcess.resizeCalls).toEqual([]);
ptyProcess.emitExit({ exitCode: 0, signal: 0 });
await manager.open({
threadId: "thread-1",
cwd: globalThis.process.cwd(),
});
const resumedSpawn = ptyAdapter.spawnInputs[1];
expect(resumedSpawn).toBeDefined();
if (!resumedSpawn) return;
expect(resumedSpawn.cols).toBe(100);
expect(resumedSpawn.rows).toBe(24);
manager.dispose();
});
it("uses default dimensions when opening a new terminal without size hints", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open({
threadId: "thread-1",
cwd: process.cwd(),
});
const spawned = ptyAdapter.spawnInputs[0];
expect(spawned).toBeDefined();
if (!spawned) return;
expect(spawned.cols).toBe(120);
expect(spawned.rows).toBe(30);
manager.dispose();
});
it("supports multiple terminals per thread with isolated sessions", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "term-2" }));
const first = ptyAdapter.processes[0];
const second = ptyAdapter.processes[1];
expect(first).toBeDefined();
expect(second).toBeDefined();
if (!first || !second) return;
await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
expect(first.writes).toEqual(["pwd\n"]);
expect(second.writes).toEqual(["ls\n"]);
expect(ptyAdapter.spawnInputs).toHaveLength(2);
manager.dispose();
});
it("clears transcript and emits cleared event", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("hello\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
await manager.clear({ threadId: "thread-1" });
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
expect(events.some((event) => event.type === "cleared")).toBe(true);
expect(
events.some(
(event) =>
event.type === "cleared" &&
event.threadId === "thread-1" &&
event.terminalId === "default",
),
).toBe(true);
manager.dispose();
});
it("restarts terminal with empty transcript and respawns pty", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
const firstProcess = ptyAdapter.processes[0];
expect(firstProcess).toBeDefined();
if (!firstProcess) return;
firstProcess.emitData("before restart\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
const snapshot = await manager.restart(openInput());
expect(snapshot.history).toBe("");
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
manager.dispose();
});
it("emits exited event and reopens with clean transcript after exit", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("old data\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
process.emitExit({ exitCode: 0, signal: 0 });
await waitFor(() => events.some((event) => event.type === "exited"));
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
expect(fs.readFileSync(historyLogPath(logsDir), "utf8")).toBe("");
manager.dispose();
});
it("emits subprocess activity events when child-process state changes", async () => {
let hasRunningSubprocess = false;
const { manager } = makeManager(5, {
subprocessChecker: async () => hasRunningSubprocess,
subprocessPollIntervalMs: 20,
});
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
await waitFor(() => events.some((event) => event.type === "started"));
expect(events.some((event) => event.type === "activity")).toBe(false);
hasRunningSubprocess = true;
await waitFor(
() =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
1_200,
);
hasRunningSubprocess = false;
await waitFor(
() =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
1_200,
);
manager.dispose();
});
it("caps persisted history to configured line limit", async () => {
const { manager, ptyAdapter } = makeManager(3);
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("line1\nline2\nline3\nline4\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0);
expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]);
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("bye\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(fs.existsSync(historyLogPath(logsDir))).toBe(false);
manager.dispose();
});
it("closes all terminals for a thread when close omits terminalId", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "sidecar" }));
const defaultProcess = ptyAdapter.processes[0];
const sidecarProcess = ptyAdapter.processes[1];
expect(defaultProcess).toBeDefined();
expect(sidecarProcess).toBeDefined();
if (!defaultProcess || !sidecarProcess) return;
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(defaultProcess.killed).toBe(true);
expect(sidecarProcess.killed).toBe(true);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false);
manager.dispose();
});
it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => {
const { manager, logsDir } = makeManager();
const legacyPath = path.join(logsDir, "thread-1.log");
const nextPath = historyLogPath(logsDir);
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
const snapshot = await manager.open(openInput());
expect(snapshot.history).toBe("legacy-line\n");
expect(fs.existsSync(nextPath)).toBe(true);
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
expect(fs.existsSync(legacyPath)).toBe(false);
manager.dispose();
});
it("retries with fallback shells when preferred shell spawn fails", async () => {
const { manager, ptyAdapter } = makeManager(5, {
shellResolver: () => "/definitely/missing-shell -l",
});
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
const snapshot = await manager.open(openInput());
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
if (process.platform === "win32") {
expect(
ptyAdapter.spawnInputs.some(
(input) => input.shell === "cmd.exe" || input.shell === "powershell.exe",
),
).toBe(true);
} else {
expect(
ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
),
).toBe(true);
}
manager.dispose();
});
it("filters app runtime env variables from terminal sessions", async () => {
const originalValues = new Map<string, string | undefined>();
const setEnv = (key: string, value: string | undefined) => {
if (!originalValues.has(key)) {
originalValues.set(key, process.env[key]);
}
if (value === undefined) {
delete process.env[key];
return;
}
process.env[key] = value;
};
const restoreEnv = () => {
for (const [key, value] of originalValues) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
};
setEnv("PORT", "5173");
setEnv("T3CODE_PORT", "3773");
setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173");
setEnv("TEST_TERMINAL_KEEP", "keep-me");
try {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.env.PORT).toBeUndefined();
expect(spawnInput.env.T3CODE_PORT).toBeUndefined();
expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined();
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
manager.dispose();
} finally {
restoreEnv();
}
});
it("injects runtime env overrides into spawned terminals", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(
openInput({
env: {
T3CODE_PROJECT_ROOT: "/repo",
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
CUSTOM_FLAG: "1",
},
}),
);
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo");
expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a");
expect(spawnInput.env.CUSTOM_FLAG).toBe("1");
manager.dispose();
});
it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => {
if (process.platform === "win32") return;
const { manager, ptyAdapter } = makeManager(5, {
shellResolver: () => "/bin/zsh",
});
await manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.shell).toBe("/bin/zsh");
expect(spawnInput.args).toEqual(["-o", "nopromptsp"]);
manager.dispose();
});
});
File diff suppressed because it is too large. Load diff
@@ -1,80 +0,0 @@
import { assert, beforeEach, describe, it, vi } from "vitest";
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
const { runProcessMock } = vi.hoisted(() => ({
runProcessMock: vi.fn<
(
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>
>(),
}));
vi.mock("./processRunner", () => ({
runProcess: runProcessMock,
}));
function processResult(
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
): ProcessRunResult {
return {
stdout: overrides.stdout,
code: overrides.code,
stderr: overrides.stderr ?? "",
signal: overrides.signal ?? null,
timedOut: overrides.timedOut ?? false,
stdoutTruncated: overrides.stdoutTruncated ?? false,
stderrTruncated: overrides.stderrTruncated ?? false,
};
}
describe("searchWorkspaceEntries git-ignore chunking", () => {
beforeEach(() => {
runProcessMock.mockReset();
vi.resetModules();
});
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
const ignoredPaths = Array.from(
{ length: 5000 },
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
);
const keptPaths = ["src/keep.ts", "docs/readme.md"];
const listedPaths = [...ignoredPaths, ...keptPaths];
let checkIgnoreCalls = 0;
runProcessMock.mockImplementation(async (_command, args, options) => {
if (args[0] === "rev-parse") {
return processResult({ code: 0, stdout: "true\n" });
}
if (args[0] === "ls-files") {
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
}
if (args[0] === "check-ignore") {
checkIgnoreCalls += 1;
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
return processResult({
code: chunkIgnored.length > 0 ? 0 : 1,
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
});
}
throw new Error(`Unexpected command: git ${args.join(" ")}`);
});
const { searchWorkspaceEntries } = await import("./workspaceEntries");
const result = await searchWorkspaceEntries({
cwd: "/virtual/workspace",
query: "",
limit: 100,
});
assert.isAbove(checkIgnoreCalls, 1);
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
});
});
-176
View File
@@ -1,176 +0,0 @@
import fs from "node:fs";
import fsPromises from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { afterEach, assert, describe, it, vi } from "vitest";
import { searchWorkspaceEntries } from "./workspaceEntries";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function writeFile(cwd: string, relativePath: string, contents = ""): void {
const absolutePath = path.join(cwd, relativePath);
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
fs.writeFileSync(absolutePath, contents, "utf8");
}
function runGit(cwd: string, args: string[]): void {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
if (result.status !== 0) {
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
}
}
describe("searchWorkspaceEntries", () => {
afterEach(() => {
vi.restoreAllMocks();
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("returns files and directories relative to cwd", async () => {
const cwd = makeTempDir("t3code-workspace-entries-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/index.ts");
writeFile(cwd, "README.md");
writeFile(cwd, ".git/HEAD");
writeFile(cwd, "node_modules/pkg/index.js");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
assert.include(paths, "src");
assert.include(paths, "src/components");
assert.include(paths, "src/components/Composer.tsx");
assert.include(paths, "README.md");
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
assert.isFalse(result.truncated);
});
it("filters and ranks entries by query", async () => {
const cwd = makeTempDir("t3code-workspace-query-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/components/composePrompt.ts");
writeFile(cwd, "docs/composition.md");
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
assert.isAbove(result.entries.length, 0);
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
});
it("excludes gitignored paths for git repositories", async () => {
const cwd = makeTempDir("t3code-workspace-gitignore-");
runGit(cwd, ["init"]);
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
writeFile(cwd, "src/keep.ts", "export {};");
writeFile(cwd, "ignored.txt", "ignore me");
writeFile(cwd, ".convex/local-storage/data.json", "{}");
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
assert.include(paths, "src");
assert.include(paths, "src/keep.ts");
assert.notInclude(paths, "ignored.txt");
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
});
it("excludes tracked paths that match ignore rules", async () => {
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
runGit(cwd, ["init"]);
writeFile(cwd, ".convex/local-storage/data.json", "{}");
writeFile(cwd, "src/keep.ts", "export {};");
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
writeFile(cwd, ".gitignore", ".convex/\n");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
assert.include(paths, "src");
assert.include(paths, "src/keep.ts");
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
});
it("excludes .convex in non-git workspaces", async () => {
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
writeFile(cwd, ".convex/local-storage/data.json", "{}");
writeFile(cwd, "src/keep.ts", "export {};");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
assert.include(paths, "src");
assert.include(paths, "src/keep.ts");
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
});
it("deduplicates concurrent index builds for the same cwd", async () => {
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
writeFile(cwd, "src/components/Composer.tsx");
let rootReadCount = 0;
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation(
(async (...args: Parameters<typeof fsPromises.readdir>) => {
if (args[0] === cwd) {
rootReadCount += 1;
await new Promise((resolve) => setTimeout(resolve, 20));
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir,
);
await Promise.all([
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
]);
assert.equal(rootReadCount, 1);
});
it("limits concurrent directory reads while walking the filesystem", async () => {
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
for (let index = 0; index < 80; index += 1) {
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
}
let activeReads = 0;
let peakReads = 0;
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation(
(async (...args: Parameters<typeof fsPromises.readdir>) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await new Promise((resolve) => setTimeout(resolve, 4));
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir,
);
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
assert.isAtMost(peakReads, 32);
});
});
-433
View File
@@ -1,433 +0,0 @@
import fs from "node:fs/promises";
import type { Dirent } from "node:fs";
import path from "node:path";
import { runProcess } from "./processRunner";
import {
projectSearchEntriesInputSchema,
type ProjectEntry,
type ProjectSearchEntriesInput,
type ProjectSearchEntriesResult,
} from "@t3tools/contracts";
const WORKSPACE_CACHE_TTL_MS = 15_000;
const WORKSPACE_CACHE_MAX_KEYS = 4;
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const IGNORED_DIRECTORY_NAMES = new Set([
".git",
".convex",
"node_modules",
".next",
".turbo",
"dist",
"build",
"out",
".cache",
]);
interface WorkspaceIndex {
scannedAt: number;
entries: ProjectEntry[];
truncated: boolean;
}
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
function toPosixPath(input: string): string {
return input.split(path.sep).join("/");
}
function parentPathOf(input: string): string | undefined {
const separatorIndex = input.lastIndexOf("/");
if (separatorIndex === -1) {
return undefined;
}
return input.slice(0, separatorIndex);
}
function basenameOf(input: string): string {
const separatorIndex = input.lastIndexOf("/");
if (separatorIndex === -1) {
return input;
}
return input.slice(separatorIndex + 1);
}
function normalizeQuery(input: string): string {
return input
.trim()
.replace(/^[@./]+/, "")
.toLowerCase();
}
function scoreEntry(entry: ProjectEntry, query: string): number {
if (!query) {
return entry.kind === "directory" ? 0 : 1;
}
const normalizedPath = entry.path.toLowerCase();
const normalizedName = basenameOf(normalizedPath);
if (normalizedName === query) return 0;
if (normalizedPath === query) return 1;
if (normalizedName.startsWith(query)) return 2;
if (normalizedPath.startsWith(query)) return 3;
if (normalizedPath.includes(`/${query}`)) return 4;
return 5;
}
function isPathInIgnoredDirectory(relativePath: string): boolean {
const firstSegment = relativePath.split("/")[0];
if (!firstSegment) return false;
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
}
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
// If output was truncated, the final token can be partial.
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function directoryAncestorsOf(relativePath: string): string[] {
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
if (segments.length <= 1) return [];
const directories: string[] = [];
for (let index = 1; index < segments.length; index += 1) {
directories.push(segments.slice(0, index).join("/"));
}
return directories;
}
async function mapWithConcurrency<TInput, TOutput>(
items: readonly TInput[],
concurrency: number,
mapper: (item: TInput, index: number) => Promise<TOutput>,
): Promise<TOutput[]> {
if (items.length === 0) {
return [];
}
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
const results = Array.from({ length: items.length }) as TOutput[];
let nextIndex = 0;
const workers = Array.from({ length: boundedConcurrency }, async () => {
while (nextIndex < items.length) {
const currentIndex = nextIndex;
nextIndex += 1;
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
}
});
await Promise.all(workers);
return results;
}
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxBufferBytes: 4_096,
}).catch(() => null);
return Boolean(
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
);
}
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
if (relativePaths.length === 0) {
return relativePaths;
}
const ignoredPaths = new Set<string>();
let chunk: string[] = [];
let chunkBytes = 0;
const flushChunk = async (): Promise<boolean> => {
if (chunk.length === 0) {
return true;
}
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
cwd,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxBufferBytes: 16 * 1024 * 1024,
outputMode: "truncate",
stdin: `${chunk.join("\0")}\0`,
}).catch(() => null);
chunk = [];
chunkBytes = 0;
if (!checkIgnore) {
return false;
}
// git-check-ignore exits with 1 when no paths match.
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
return false;
}
const matchedIgnoredPaths = splitNullSeparatedPaths(
checkIgnore.stdout,
Boolean(checkIgnore.stdoutTruncated),
);
for (const ignoredPath of matchedIgnoredPaths) {
ignoredPaths.add(ignoredPath);
}
return true;
};
for (const relativePath of relativePaths) {
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
if (
chunk.length > 0 &&
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
!(await flushChunk())
) {
return relativePaths;
}
chunk.push(relativePath);
chunkBytes += relativePathBytes;
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
return relativePaths;
}
}
if (!(await flushChunk())) {
return relativePaths;
}
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
}
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
if (!(await isInsideGitWorkTree(cwd))) {
return null;
}
const listedFiles = await runProcess(
"git",
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
{
cwd,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxBufferBytes: 16 * 1024 * 1024,
outputMode: "truncate",
},
).catch(() => null);
if (!listedFiles || listedFiles.code !== 0) {
return null;
}
const listedPaths = splitNullSeparatedPaths(
listedFiles.stdout,
Boolean(listedFiles.stdoutTruncated),
)
.map((entry) => toPosixPath(entry))
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
const directorySet = new Set<string>();
for (const filePath of filePaths) {
for (const directoryPath of directoryAncestorsOf(filePath)) {
if (!isPathInIgnoredDirectory(directoryPath)) {
directorySet.add(directoryPath);
}
}
}
const directoryEntries: ProjectEntry[] = [...directorySet]
.toSorted((left, right) => left.localeCompare(right))
.map((directoryPath) => ({
path: directoryPath,
kind: "directory",
parentPath: parentPathOf(directoryPath),
}));
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
.toSorted((left, right) => left.localeCompare(right))
.map((filePath) => ({
path: filePath,
kind: "file",
parentPath: parentPathOf(filePath),
}));
const entries = [...directoryEntries, ...fileEntries];
return {
scannedAt: Date.now(),
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
};
}
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
if (gitIndexed) {
return gitIndexed;
}
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
let pendingDirectories: string[] = [""];
const entries: ProjectEntry[] = [];
let truncated = false;
while (pendingDirectories.length > 0 && !truncated) {
const currentDirectories = pendingDirectories;
pendingDirectories = [];
const directoryEntries = await mapWithConcurrency(
currentDirectories,
WORKSPACE_SCAN_READDIR_CONCURRENCY,
async (relativeDir) => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
try {
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
} catch (error) {
if (!relativeDir) {
throw new Error(
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
{ cause: error },
);
}
return { relativeDir, dirents: null };
}
},
);
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
const { relativeDir, dirents } = directoryEntry;
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
dirents.sort((left, right) => left.name.localeCompare(right.name));
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
for (const dirent of dirents) {
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
continue;
}
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
candidates.push({ dirent, relativePath });
}
return candidates;
});
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
candidateEntries.map((entry) => entry.relativePath),
);
const allowedPathSet = shouldFilterWithGitIgnore
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
: null;
for (const candidateEntries of candidateEntriesByDirectory) {
for (const candidate of candidateEntries) {
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
continue;
}
const entry: ProjectEntry = {
path: candidate.relativePath,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
parentPath: parentPathOf(candidate.relativePath),
};
entries.push(entry);
if (candidate.dirent.isDirectory()) {
pendingDirectories.push(candidate.relativePath);
}
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
truncated = true;
break;
}
}
if (truncated) {
break;
}
}
}
return {
scannedAt: Date.now(),
entries,
truncated,
};
}
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
const cached = workspaceIndexCache.get(cwd);
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
return cached;
}
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
if (inFlight) {
return inFlight;
}
const nextPromise = buildWorkspaceIndex(cwd)
.then((next) => {
workspaceIndexCache.set(cwd, next);
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
const oldestKey = workspaceIndexCache.keys().next().value;
if (!oldestKey) break;
workspaceIndexCache.delete(oldestKey);
}
return next;
})
.finally(() => {
inFlightWorkspaceIndexBuilds.delete(cwd);
});
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
return nextPromise;
}
export async function searchWorkspaceEntries(
input: ProjectSearchEntriesInput,
): Promise<ProjectSearchEntriesResult> {
const parsed = projectSearchEntriesInputSchema.parse(input);
const index = await getWorkspaceIndex(parsed.cwd);
const normalizedQuery = normalizeQuery(parsed.query);
const candidates = normalizedQuery
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
: index.entries;
const ranked = candidates.toSorted((left, right) => {
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
if (scoreDelta !== 0) return scoreDelta;
return left.path.localeCompare(right.path);
});
return {
entries: ranked.slice(0, parsed.limit),
truncated: index.truncated || ranked.length > parsed.limit,
};
}
File diff suppressed because it is too large. Load diff
-509
View File
@@ -1,509 +0,0 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import type { Duplex } from "node:stream";
import {
EDITORS,
WS_CHANNELS,
WS_METHODS,
type TerminalEvent,
type WsPush,
type WsRequest,
type WsResponse,
wsRequestSchema,
} from "@t3tools/contracts";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import { GitManager } from "./gitManager";
import {
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
} from "./git";
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".map": "application/json",
};
export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
function parseBooleanEnv(value: string | undefined): boolean | undefined {
if (value === undefined) return undefined;
const normalized = value.trim().toLowerCase();
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off"].includes(normalized)) return false;
return undefined;
}
export function createServer(options: ServerOptions) {
const {
port,
host,
cwd,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
} = options;
const providerManager = new ProviderManager();
const terminalManager = providedTerminalManager ?? new TerminalManager();
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
logger.event("outgoing push", {
channel: push.channel,
recipients,
payload: push.data,
});
}
// Forward provider events to all connected WebSocket clients
providerManager.on("event", (event) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.providerEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
});
const onTerminalEvent = (event: TerminalEvent) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.terminalEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
};
terminalManager.on("event", onTerminalEvent);
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
// In dev mode, redirect to Vite dev server
if (devUrl) {
res.writeHead(302, { Location: devUrl });
res.end();
return;
}
// Serve static files from the web app build
if (!staticDir) {
res.writeHead(503, { "Content-Type": "text/plain" });
res.end("No static directory configured and no dev URL set.");
return;
}
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
let filePath = path.join(staticDir, url.pathname);
// SPA fallback: if no file extension and not found, serve index.html
const ext = path.extname(filePath);
if (!ext) {
filePath = path.join(filePath, "index.html");
}
fs.stat(filePath, (err, stats) => {
if (err || !stats?.isFile()) {
// SPA fallback
const indexPath = path.join(staticDir, "index.html");
fs.readFile(indexPath, (readErr, data) => {
if (readErr) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
return;
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(data);
});
return;
}
const fileExt = path.extname(filePath);
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
});
});
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
}
httpServer.on("upgrade", (request, socket, head) => {
if (authToken) {
let providedToken: string | null = null;
try {
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
providedToken = url.searchParams.get("token");
} catch {
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
return;
}
if (providedToken !== authToken) {
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
return;
}
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request);
});
});
wss.on("connection", (ws) => {
clients.add(ws);
// Send welcome message with project info
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: { cwd, projectName },
};
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
ws.on("close", () => {
clients.delete(ws);
});
ws.on("error", () => {
clients.delete(ws);
});
});
async function handleMessage(ws: WebSocket, raw: unknown) {
let request: WsRequest;
try {
const parsed = JSON.parse(String(raw));
request = wsRequestSchema.parse(parsed);
} catch {
const errorResponse: WsResponse = {
id: "unknown",
error: { message: "Invalid request format" },
};
ws.send(JSON.stringify(errorResponse));
return;
}
try {
const result = await routeRequest(request);
const response: WsResponse = { id: request.id, result };
ws.send(JSON.stringify(response));
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown server error";
const response: WsResponse = {
id: request.id,
error: { message },
};
ws.send(JSON.stringify(response));
}
}
async function routeRequest(request: WsRequest): Promise<unknown> {
switch (request.method) {
case WS_METHODS.providersStartSession:
return providerManager.startSession(request.params as never);
case WS_METHODS.providersSendTurn:
return providerManager.sendTurn(request.params as never);
case WS_METHODS.providersInterruptTurn:
return providerManager.interruptTurn(request.params as never);
case WS_METHODS.providersRespondToRequest:
return providerManager.respondToRequest(request.params as never);
case WS_METHODS.providersStopSession: {
providerManager.stopSession(request.params as never);
return undefined;
}
case WS_METHODS.providersListSessions:
return providerManager.listSessions();
case WS_METHODS.providersListCheckpoints:
return providerManager.listCheckpoints(request.params as never);
case WS_METHODS.providersGetCheckpointDiff:
return providerManager.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint:
return providerManager.revertToCheckpoint(request.params as never);
case WS_METHODS.projectsList:
return projectRegistry.list();
case WS_METHODS.projectsAdd:
return projectRegistry.add(request.params as never);
case WS_METHODS.projectsRemove:
projectRegistry.remove(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.projectsUpdateScripts:
return projectRegistry.updateScripts(request.params as never);
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
cwd: string;
editor: string;
};
if (!params?.cwd) throw new Error("cwd is required");
const editorDef = EDITORS.find((e) => e.id === params.editor);
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
let command: string;
let args: string[];
if (editorDef.command) {
command = editorDef.command;
args = [params.cwd];
} else if (editorDef.id === "file-manager") {
// Use platform-specific file manager command
switch (process.platform) {
case "darwin":
command = "open";
break;
case "win32":
command = "explorer";
break;
default:
command = "xdg-open";
break;
}
args = [params.cwd];
} else {
return undefined;
}
const child = spawn(command, args, {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
/* ignore spawn failures for detached editors */
});
child.unref();
return undefined;
}
case WS_METHODS.gitStatus:
return gitManager.status(request.params as never);
case WS_METHODS.gitPull:
return pullGitBranch(request.params as never);
case WS_METHODS.gitRunStackedAction:
return gitManager.runStackedAction(request.params as never);
case WS_METHODS.gitListBranches:
return listGitBranches(request.params as never);
case WS_METHODS.gitCreateWorktree:
return createGitWorktree(request.params as never);
case WS_METHODS.gitRemoveWorktree:
return removeGitWorktree(request.params as never);
case WS_METHODS.gitCreateBranch:
return createGitBranch(request.params as never);
case WS_METHODS.gitCheckout:
return checkoutGitBranch(request.params as never);
case WS_METHODS.gitInit:
return initGitRepo(request.params as never);
case WS_METHODS.terminalOpen:
return terminalManager.open(request.params as never);
case WS_METHODS.terminalWrite:
await terminalManager.write(request.params as never);
return undefined;
case WS_METHODS.terminalResize:
await terminalManager.resize(request.params as never);
return undefined;
case WS_METHODS.terminalClear:
await terminalManager.clear(request.params as never);
return undefined;
case WS_METHODS.terminalRestart:
return terminalManager.restart(request.params as never);
case WS_METHODS.terminalClose:
await terminalManager.close(request.params as never);
return undefined;
case WS_METHODS.serverGetConfig:
return {
cwd,
keybindings: keybindingsConfig,
};
case WS_METHODS.serverUpsertKeybinding:
keybindingsConfig = upsertKeybindingRule(logger, request.params);
return {
keybindings: keybindingsConfig,
};
default:
throw new Error(`Unknown method: ${request.method}`);
}
}
function start() {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
reject(error);
};
httpServer.once("error", onError);
const onListening = () => {
httpServer.off("error", onError);
resolve();
};
if (host) {
httpServer.listen(port, host, onListening);
return;
}
httpServer.listen(port, onListening);
});
}
async function stop(): Promise<void> {
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
for (const client of clients) {
client.close();
}
clients.clear();
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" ||
error.message.toLowerCase().includes("not running")
);
};
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
reject(error);
return;
}
resolve();
});
});
const closeHttpServer = new Promise<void>((resolve, reject) => {
httpServer.close((error) => {
if (error && !isServerNotRunningError(error)) {
reject(error);
return;
}
resolve();
});
});
await Promise.all([closeWebSocketServer, closeHttpServer]);
}
return { start, stop, httpServer };
}
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node"],
"lib": ["ES2023", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
-14
View File
@@ -1,14 +0,0 @@
import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@t3tools/contracts", "zod"],
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
},
});
-11
View File
@@ -1,11 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"start": {
"dependsOn": ["build"],
"cache": false,
"persistent": true,
},
},
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@acme/t3-runtime",
"version": "0.0.0",
"private": true,
"bin": {
"t3": "dist/cli.js"
},
"type": "module",
"scripts": {
"dev": "tsx src/cli.ts",
"build": "tsup --config tsup.config.ts",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@acme/contracts": "workspace:*",
"@acme/runtime-core": "workspace:*",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsup": "^8.3.5",
"tsx": "^4.20.3",
"typescript": "^5.7.3"
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1175
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+818
View File
@@ -0,0 +1,818 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import {
EDITORS,
DEFAULT_MODEL,
appBootstrapResultSchema,
appHealthResultSchema,
dialogsPickFolderResultSchema,
type ProviderSession,
type WsClientMessage,
type WsResponseMessage,
type WsServerMessage,
WS_EVENT_CHANNELS,
WS_ERROR_CODE_MAX_CHARS,
WS_ERROR_MESSAGE_MAX_CHARS,
WS_CLOSE_CODES,
WS_CLOSE_REASONS,
agentConfigSchema,
agentSessionIdSchema,
agentWriteInputSchema,
newTodoInputSchema,
todoIdSchema,
providerInterruptTurnInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionListSchema,
providerSessionStartInputSchema,
providerSessionSchema,
providerStopSessionInputSchema,
providerTurnStartResultSchema,
type TerminalCommandInput,
shellOpenInEditorInputSchema,
terminalCommandResultSchema,
terminalCommandInputSchema,
todoListSchema,
wsClientMessageSchema,
wsNativeApiMethodSchema,
wsServerMessageSchema,
} from "@acme/contracts";
import { ProcessManager, ProviderManager, TodoStore } from "@acme/runtime-core";
interface RuntimeApiServerOptions {
port: number;
launchCwd: string;
bootstrapSessionTimeoutMs?: number;
authToken?: string;
}
interface RuntimeApiServer {
wsUrl: string;
close: () => Promise<void>;
}
interface JsonRpcErrorResult {
code: string;
message: string;
}
const BOOTSTRAP_SESSION_TIMEOUT_MS = 3_000;
const MAX_BOOTSTRAP_SESSION_TIMEOUT_MS = 120_000;
const MAX_WS_CLIENT_PAYLOAD_BYTES = 5 * 1024 * 1024;
const MAX_ERROR_PATH_CHARS = 2_048;
interface BootstrapSessionResult {
session: ProviderSession;
bootstrapError: string | undefined;
}
type WsServerEventMessage = Extract<WsServerMessage, { type: "event" }>;
function raceWithTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
timeoutMessage: string,
): Promise<T> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(timeoutMessage));
}, timeoutMs);
timeout.unref();
promise.then(
(value) => {
clearTimeout(timeout);
resolve(value);
},
(error) => {
clearTimeout(timeout);
reject(error);
},
);
});
}
function responseSuccess(id: string, result: unknown): WsResponseMessage {
return {
type: "response",
id,
ok: true,
result: result === undefined ? null : result,
};
}
function responseError(id: string, error: JsonRpcErrorResult): WsResponseMessage {
const normalizedCode = normalizeErrorField(
error.code,
"request_failed",
WS_ERROR_CODE_MAX_CHARS,
);
const normalizedMessage = normalizeErrorField(
error.message,
"Request failed",
WS_ERROR_MESSAGE_MAX_CHARS,
);
return {
type: "response",
id,
ok: false,
error: {
code: normalizedCode,
message: normalizedMessage,
},
};
}
function normalizeErrorField(value: string, fallback: string, maxChars: number): string {
const trimmed = value.trim();
const safeValue = trimmed.length > 0 ? trimmed : fallback;
if (safeValue.length <= maxChars) {
return safeValue;
}
if (maxChars <= 1) {
return safeValue.slice(0, maxChars);
}
return `${safeValue.slice(0, maxChars - 1)}…`;
}
function summarizePathForError(candidatePath: string): string {
if (candidatePath.length <= MAX_ERROR_PATH_CHARS) {
return candidatePath;
}
const prefixLength = Math.floor((MAX_ERROR_PATH_CHARS - 1) / 2);
const suffixLength = MAX_ERROR_PATH_CHARS - 1 - prefixLength;
return `${candidatePath.slice(0, prefixLength)}…${candidatePath.slice(-suffixLength)}`;
}
function sendMessage(socket: WebSocket, message: unknown): void {
if (socket.readyState !== WebSocket.OPEN) {
return;
}
const parsedMessage = wsServerMessageSchema.safeParse(message);
if (!parsedMessage.success) {
return;
}
try {
socket.send(JSON.stringify(parsedMessage.data));
} catch {
// Best-effort event delivery. Socket may have transitioned states.
}
}
function decodeClientMessage(raw: RawData): string | null {
if (typeof raw === "string") {
return raw;
}
if (raw instanceof Buffer) {
return raw.toString("utf8");
}
if (raw instanceof ArrayBuffer) {
return Buffer.from(raw).toString("utf8");
}
if (Array.isArray(raw)) {
return Buffer.concat(raw).toString("utf8");
}
return null;
}
function openPathInFileManager(targetPath: string): void {
const command =
process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";
const child = spawn(command, [targetPath], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
// Best-effort shell handoff.
});
child.unref();
}
async function tryCommand(command: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
const child = spawn(command, args, {
stdio: ["ignore", "pipe", "ignore"],
});
let output = "";
child.stdout.on("data", (chunk: Buffer) => {
output += chunk.toString();
});
child.on("error", () => {
resolve(null);
});
child.on("close", (code) => {
if (code !== 0) {
resolve(null);
return;
}
const trimmed = output.trim();
resolve(trimmed.length > 0 ? trimmed : null);
});
});
}
async function pickFolder(): Promise<string | null> {
if (process.platform === "darwin") {
const script =
'try\nset selectedFolder to POSIX path of (choose folder with prompt "Choose a project folder")\nreturn selectedFolder\non error\nreturn ""\nend try';
const result = await tryCommand("osascript", ["-e", script]);
return result && result.length > 0 ? result : null;
}
if (process.platform === "win32") {
const powershellScript = [
"Add-Type -AssemblyName System.Windows.Forms",
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
'$dialog.Description = "Choose a project folder"',
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {",
" Write-Output $dialog.SelectedPath",
"}",
].join("; ");
const result = await tryCommand("powershell", ["-NoProfile", "-Command", powershellScript]);
return result && result.length > 0 ? result : null;
}
const zenity = await tryCommand("zenity", ["--file-selection", "--directory"]);
if (zenity) {
return zenity;
}
const kdialog = await tryCommand("kdialog", ["--getexistingdirectory"]);
if (kdialog) {
return kdialog;
}
return null;
}
async function runTerminalCommand(
parsed: TerminalCommandInput,
defaultCwd: string,
) {
const providedCwd = parsed.cwd ?? defaultCwd;
const resolvedCwd = resolveExistingDirectoryFromBase(
providedCwd,
"Working directory",
defaultCwd,
);
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", parsed.command] : ["-lc", parsed.command];
return new Promise<{
stdout: string;
stderr: string;
code: number | null;
signal: string | null;
timedOut: boolean;
}>((resolve, reject) => {
const child = spawn(shellPath, args, {
cwd: resolvedCwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 1_000).unref();
}, parsed.timeoutMs ?? 30_000);
timeout.unref();
child.stdout?.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr?.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
resolve({
stdout,
stderr,
code: code ?? null,
signal: signal ?? null,
timedOut,
});
});
});
}
function resolveExistingDirectory(targetPath: string, label: string): string {
if (typeof targetPath !== "string" || targetPath.trim().length === 0) {
throw new Error(`${label} must be a non-empty path.`);
}
const candidate = path.resolve(targetPath);
let stats: fs.Stats;
try {
stats = fs.statSync(candidate);
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
const safeCandidate = summarizePathForError(candidate);
if (code && code !== "ENOENT") {
throw new Error(`Failed to access ${label.toLowerCase()}: ${safeCandidate} (${code})`, {
cause: error,
});
}
throw new Error(`${label} does not exist: ${safeCandidate}`, {
cause: error,
});
}
if (!stats.isDirectory()) {
throw new Error(`${label} is not a directory: ${summarizePathForError(candidate)}`);
}
return candidate;
}
function resolveExistingDirectoryFromBase(
targetPath: string,
label: string,
baseDirectory: string,
): string {
if (typeof targetPath !== "string" || targetPath.trim().length === 0) {
throw new Error(`${label} must be a non-empty path.`);
}
const candidate = path.isAbsolute(targetPath)
? path.resolve(targetPath)
: path.resolve(baseDirectory, targetPath);
return resolveExistingDirectory(candidate, label);
}
export async function startRuntimeApiServer(
options: RuntimeApiServerOptions,
): Promise<RuntimeApiServer> {
if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65_535) {
throw new Error("Invalid runtime port: expected integer between 0 and 65535.");
}
const launchCwd = resolveExistingDirectory(options.launchCwd, "Invalid launchCwd");
if (options.authToken !== undefined && typeof options.authToken !== "string") {
throw new Error("Invalid runtime auth token: expected non-empty string.");
}
const authToken = options.authToken?.trim();
if (options.authToken !== undefined && !authToken) {
throw new Error("Invalid runtime auth token: expected non-empty string.");
}
const bootstrapSessionTimeoutMs =
options.bootstrapSessionTimeoutMs ?? BOOTSTRAP_SESSION_TIMEOUT_MS;
if (
!Number.isInteger(bootstrapSessionTimeoutMs) ||
bootstrapSessionTimeoutMs <= 0 ||
bootstrapSessionTimeoutMs > MAX_BOOTSTRAP_SESSION_TIMEOUT_MS
) {
throw new Error(
`Invalid bootstrapSessionTimeoutMs: expected integer between 1 and ${MAX_BOOTSTRAP_SESSION_TIMEOUT_MS}.`,
);
}
const providerManager = new ProviderManager();
const processManager = new ProcessManager();
const todoStore = new TodoStore(path.join(os.homedir(), ".t3", "todos.json"));
await todoStore.init();
let activeClient: WebSocket | null = null;
let launchSessionPromise: Promise<BootstrapSessionResult> | null = null;
let bootstrapFallbackSession: ProviderSession | null = null;
const emitEvent = <TChannel extends WsServerEventMessage["channel"]>(
channel: TChannel,
payload: Extract<WsServerEventMessage, { channel: TChannel }>["payload"],
) => {
if (!activeClient) {
return;
}
sendMessage(activeClient, {
type: "event",
channel,
payload,
});
};
processManager.on("output", (chunk) => {
emitEvent(WS_EVENT_CHANNELS.agentOutput, chunk);
});
processManager.on("exit", (payload) => {
emitEvent(WS_EVENT_CHANNELS.agentExit, payload);
});
providerManager.on("event", (payload) => {
emitEvent(WS_EVENT_CHANNELS.providerEvent, payload);
});
const createBootstrapErrorSession = (message: string): ProviderSession => {
const timestamp = new Date().toISOString();
return {
sessionId: `bootstrap-error-${Date.now()}`,
provider: "codex",
status: "error",
cwd: launchCwd,
model: DEFAULT_MODEL,
createdAt: timestamp,
updatedAt: timestamp,
lastError: message,
};
};
const ensureLaunchSession = async (): Promise<BootstrapSessionResult> => {
const isLaunchProjectSession = (session: ProviderSession) => {
if (!session.cwd) {
return false;
}
return path.resolve(session.cwd) === launchCwd;
};
const existingSession = providerManager
.listSessions()
.find((session) => isLaunchProjectSession(session) && session.status !== "closed");
if (existingSession) {
bootstrapFallbackSession = null;
return {
session: existingSession,
bootstrapError: undefined,
};
}
if (bootstrapFallbackSession) {
return {
session: bootstrapFallbackSession,
bootstrapError: bootstrapFallbackSession.lastError,
};
}
if (launchSessionPromise) {
return launchSessionPromise;
}
launchSessionPromise = (async () => {
try {
const startedSession = await raceWithTimeout(
providerManager.startSession({
provider: "codex",
cwd: launchCwd,
model: DEFAULT_MODEL,
approvalPolicy: "never",
sandboxMode: "danger-full-access",
}),
bootstrapSessionTimeoutMs,
"Timed out starting launch session.",
);
bootstrapFallbackSession = null;
return {
session: startedSession,
bootstrapError: undefined,
};
} catch (error) {
const message =
error instanceof Error
? error.message
: "Failed to initialize Codex launch session.";
const fallbackSession = (() => {
if (!bootstrapFallbackSession) {
return createBootstrapErrorSession(message);
}
return Object.assign({}, bootstrapFallbackSession, {
lastError: message,
updatedAt: new Date().toISOString(),
}) as ProviderSession;
})();
bootstrapFallbackSession = fallbackSession;
return {
session: fallbackSession,
bootstrapError: message,
};
} finally {
launchSessionPromise = null;
}
})();
const pendingLaunchSessionPromise = launchSessionPromise;
if (!pendingLaunchSessionPromise) {
throw new Error("Could not initialize launch session promise.");
}
return pendingLaunchSessionPromise;
};
const wss = new WebSocketServer({
host: "127.0.0.1",
port: options.port,
maxPayload: MAX_WS_CLIENT_PAYLOAD_BYTES,
perMessageDeflate: false,
});
const isAuthorizedConnection = (requestUrl: string | undefined) => {
if (!requestUrl) {
return authToken === null;
}
try {
const request = new URL(requestUrl, "ws://127.0.0.1");
if (request.pathname !== "/") {
return false;
}
if (!authToken) {
return request.searchParams.size === 0;
}
const tokens = request.searchParams.getAll("token");
return (
request.searchParams.size === 1 &&
tokens.length === 1 &&
tokens[0] === authToken
);
} catch {
return false;
}
};
const resolveMethod = async (method: string, params: unknown) => {
const parsedMethod = wsNativeApiMethodSchema.safeParse(method);
if (!parsedMethod.success) {
throw new Error(`Unknown API method: ${method}`);
}
const apiMethod = parsedMethod.data;
switch (apiMethod) {
case "app.bootstrap": {
const bootstrap = await ensureLaunchSession();
const payload = {
launchCwd,
projectName: path.basename(launchCwd) || launchCwd,
provider: "codex",
model: bootstrap.session.model ?? DEFAULT_MODEL,
session: bootstrap.session,
...(bootstrap.bootstrapError
? { bootstrapError: bootstrap.bootstrapError }
: {}),
};
return appBootstrapResultSchema.parse(payload);
}
case "app.health": {
const payload = {
status: "ok",
launchCwd,
sessionCount: providerManager.listSessions().length,
activeClientConnected: activeClient !== null,
};
return appHealthResultSchema.parse(payload);
}
case "todos.list":
return todoListSchema.parse(await todoStore.list());
case "todos.add":
return todoListSchema.parse(await todoStore.add(newTodoInputSchema.parse(params)));
case "todos.toggle":
return todoListSchema.parse(await todoStore.toggle(todoIdSchema.parse(params)));
case "todos.remove":
return todoListSchema.parse(await todoStore.remove(todoIdSchema.parse(params)));
case "dialogs.pickFolder":
return dialogsPickFolderResultSchema.parse(await pickFolder());
case "terminal.run":
return terminalCommandResultSchema.parse(
await runTerminalCommand(terminalCommandInputSchema.parse(params), launchCwd),
);
case "agent.spawn":
return agentSessionIdSchema.parse(processManager.spawn(agentConfigSchema.parse(params)));
case "agent.kill":
processManager.kill(agentSessionIdSchema.parse(params));
return null;
case "agent.write": {
const parsed = agentWriteInputSchema.parse(params);
processManager.write(parsed.sessionId, parsed.data);
return null;
}
case "providers.startSession": {
const session = await providerManager.startSession(
providerSessionStartInputSchema.parse(params),
);
bootstrapFallbackSession = null;
return providerSessionSchema.parse(session);
}
case "providers.sendTurn":
return providerTurnStartResultSchema.parse(
await providerManager.sendTurn(providerSendTurnInputSchema.parse(params)),
);
case "providers.interruptTurn":
await providerManager.interruptTurn(providerInterruptTurnInputSchema.parse(params));
return null;
case "providers.respondToRequest":
await providerManager.respondToRequest(providerRespondToRequestInputSchema.parse(params));
return null;
case "providers.stopSession":
providerManager.stopSession(providerStopSessionInputSchema.parse(params));
return null;
case "providers.listSessions":
return providerSessionListSchema.parse(providerManager.listSessions());
case "shell.openInEditor": {
const parsed = shellOpenInEditorInputSchema.parse(params);
const targetPath = resolveExistingDirectoryFromBase(parsed.cwd, "Editor target", launchCwd);
const editor = EDITORS.find((entry) => entry.id === parsed.editor);
if (!editor) {
throw new Error(`Unknown editor: ${parsed.editor}`);
}
if (!editor.command) {
openPathInFileManager(targetPath);
return null;
}
const child = spawn(editor.command, [targetPath], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
// Best-effort editor launch.
});
child.unref();
return null;
}
default: {
const unreachableMethod: never = apiMethod;
throw new Error(`Unknown API method: ${unreachableMethod}`);
}
}
};
wss.on("connection", (socket, request) => {
if (!isAuthorizedConnection(request.url)) {
socket.close(WS_CLOSE_CODES.unauthorized, WS_CLOSE_REASONS.unauthorized);
return;
}
if (activeClient && activeClient !== socket) {
activeClient.close(
WS_CLOSE_CODES.replacedByNewClient,
WS_CLOSE_REASONS.replacedByNewClient,
);
}
activeClient = socket;
sendMessage(socket, {
type: "hello",
version: 1,
launchCwd,
});
socket.on("message", async (raw) => {
const decoded = decodeClientMessage(raw);
if (!decoded) {
return;
}
const maybeParsed = (() => {
try {
return JSON.parse(decoded) as unknown;
} catch {
return null;
}
})();
if (!maybeParsed) {
return;
}
const parsed = wsClientMessageSchema.safeParse(maybeParsed);
if (!parsed.success) {
return;
}
const message = parsed.data as WsClientMessage;
try {
const result = await resolveMethod(message.method, message.params);
sendMessage(socket, responseSuccess(message.id, result));
} catch (error) {
sendMessage(
socket,
responseError(message.id, {
code: "request_failed",
message: error instanceof Error ? error.message : "Request failed",
}),
);
}
});
socket.on("close", () => {
if (activeClient === socket) {
activeClient = null;
}
});
socket.on("error", () => {
// Connection-level protocol/socket errors are expected occasionally
// (for example oversized client payloads). Keep server process alive.
if (activeClient === socket && socket.readyState !== WebSocket.OPEN) {
activeClient = null;
}
});
});
try {
await new Promise<void>((resolve, reject) => {
if (wss.address()) {
resolve();
return;
}
const onListening = () => {
wss.off("error", onError);
resolve();
};
const onError = (error: Error) => {
wss.off("listening", onListening);
reject(error);
};
wss.once("listening", onListening);
wss.once("error", onError);
});
} catch (error) {
processManager.killAll();
providerManager.stopAll();
providerManager.dispose();
await new Promise<void>((resolve) => {
try {
wss.close(() => resolve());
} catch {
resolve();
}
});
throw error;
}
const address = wss.address();
const resolvedPort =
typeof address === "object" && address !== null ? address.port : options.port;
const wsBaseUrl = `ws://127.0.0.1:${resolvedPort}`;
const wsUrl = authToken
? `${wsBaseUrl}?token=${encodeURIComponent(authToken)}`
: wsBaseUrl;
let closePromise: Promise<void> | null = null;
return {
wsUrl,
close() {
if (closePromise) {
return closePromise;
}
closePromise = (async () => {
processManager.killAll();
providerManager.stopAll();
providerManager.dispose();
activeClient = null;
for (const client of wss.clients) {
client.terminate();
}
await new Promise<void>((resolve) => {
wss.close(() => resolve());
});
})();
return closePromise;
},
};
}
+56
View File
@@ -0,0 +1,56 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const RUNTIME_SOURCE_FILES = ["cli.ts", "runtimeApiServer.ts"] as const;
describe("runtime architecture boundaries", () => {
it("keeps runtime API server wired through runtime-core services", () => {
const sourcePath = path.resolve(import.meta.dirname, "runtimeApiServer.ts");
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).toContain("from \"@acme/runtime-core\"");
expect(source).toContain("ProcessManager");
expect(source).toContain("ProviderManager");
expect(source).toContain("TodoStore");
});
for (const fileName of RUNTIME_SOURCE_FILES) {
it(`avoids direct desktop service imports in ${fileName}`, () => {
const sourcePath = path.resolve(import.meta.dirname, fileName);
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).not.toContain("../../desktop/src/");
});
}
it("does not rely on a legacy desktop workspace package", () => {
const legacyDesktopPackagePath = path.resolve(
import.meta.dirname,
"..",
"..",
"desktop",
"package.json",
);
expect(fs.existsSync(legacyDesktopPackagePath)).toBe(false);
});
it("keeps runtime-core bundled into published t3 runtime output", () => {
const tsupConfigPath = path.resolve(import.meta.dirname, "..", "tsup.config.ts");
const tsupConfigSource = fs.readFileSync(tsupConfigPath, "utf8");
expect(tsupConfigSource).toContain("\"@acme/runtime-core\"");
expect(tsupConfigSource).toContain("noExternal");
});
it("keeps smoke tests independent from real codex installation", () => {
const smokeScriptPath = path.resolve(import.meta.dirname, "..", "scripts", "smoke-test.mjs");
const smokeScriptSource = fs.readFileSync(smokeScriptPath, "utf8");
expect(smokeScriptSource).toContain("../../../test-support/fakeCodexAppServer.mjs");
expect(smokeScriptSource).toContain("createFakeCodexAppServerBinary");
expect(smokeScriptSource).toContain("PATH: `${fakeCodex.tempDir}${path.delimiter}");
expect(smokeScriptSource).toContain("fs.rmSync(fakeCodex.tempDir");
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src", "tsup.config.ts"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/cli.ts"],
format: ["esm"],
dts: true,
clean: true,
noExternal: ["@acme/contracts", "@acme/runtime-core"],
outDir: "dist",
});
-27
View File
@@ -1,27 +0,0 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-mira",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"menuColor": "default",
"menuAccent": "bold",
"aliases": {
"components": "~/components",
"utils": "~/lib/utils",
"ui": "~/components/ui",
"lib": "~/lib",
"hooks": "~/hooks"
},
"registries": {
"@coss": "https://coss.com/ui/r/{name}.json"
}
}
-18
View File
@@ -1,18 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
rel="stylesheet"
/>
<title>T3 Code</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
-278
View File
@@ -1,278 +0,0 @@
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { Activity, Suspense, lazy, useEffect, useRef } from "react";
import ChatView from "./components/ChatView";
import Sidebar from "./components/Sidebar";
import { isElectron } from "./env";
import { DEFAULT_MODEL } from "./model-logic";
import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi";
import { useMediaQuery } from "./hooks/useMediaQuery";
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
import { Sheet, SheetPopup } from "./components/ui/sheet";
import { invalidateGitQueries } from "./lib/gitReactQuery";
const DiffPanel = lazy(() => import("./components/DiffPanel"));
const DiffWorkerPoolProvider = lazy(() =>
import("./components/DiffPanel").then((module) => ({
default: module.DiffWorkerPoolProvider,
})),
);
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
const DiffPanelWrapper = (props: { children: React.ReactNode; sheet: boolean }) => {
const { state, dispatch } = useStore();
if (props.sheet) {
return (
<Sheet
open={state.diffOpen}
onOpenChange={(open) => {
if (!open) {
dispatch({ type: "CLOSE_DIFF" });
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className="w-[min(88vw,820px)] max-w-[820px] p-0"
>
{props.children}
</SheetPopup>
</Sheet>
);
}
return (
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
{props.children}
</aside>
);
};
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
if (event.method === "turn/completed") {
void invalidateGitQueries(queryClient);
}
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch, queryClient]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
dispatch({
type: "APPLY_TERMINAL_EVENT",
event,
});
});
}, [api, dispatch]);
return null;
}
function AutoProjectBootstrap() {
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((p) => p.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
// Ensure a thread is active
const existingThread = state.threads.find((t) => t.projectId === existing.id);
if (existingThread && !state.activeThreadId) {
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: existingThread.id,
});
}
return;
}
bootstrappedRef.current = true;
// Create project + thread from server cwd
const projectId = crypto.randomUUID();
dispatch({
type: "ADD_PROJECT",
project: {
id: projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
},
});
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
turnDiffSummaries: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
});
}, [state.projects, state.threads, state.activeThreadId, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
const api = useNativeApi();
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const attemptBootstrap = async () => {
try {
const projects = await api.projects.list();
if (disposed) return;
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: project.scripts,
})),
});
bootstrappedRef.current = true;
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void attemptBootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
return null;
}
function Layout() {
const api = useNativeApi();
const { state } = useStore();
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const diffLoadingFallback =
!state.diffOpen || shouldUseDiffSheet ? (
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</div>
) : (
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</aside>
);
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<Sidebar />
<ChatView />
<Activity mode={state.diffOpen ? "visible" : "hidden"}>
<DiffPanelWrapper sheet={shouldUseDiffSheet}>
<Suspense fallback={diffLoadingFallback}>
<DiffWorkerPoolProvider>
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
</DiffWorkerPoolProvider>
</Suspense>
</DiffPanelWrapper>
</Activity>
</div>
);
}
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ToastProvider>
<AnchoredToastProvider>
<Layout />
</AnchoredToastProvider>
</ToastProvider>
</StoreProvider>
</QueryClientProvider>
);
}
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more