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
197 changed files with 19057 additions and 23414 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:
-95
View File
@@ -1,95 +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+shift+o", "command": "chat.new" },
{ "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)
- `chat.new`: create a new chat thread for the active project
- `editor.openFavorite`: open current project/worktree in the last-used editor
### 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,30 +11,24 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@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>
);
}
+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>
);
}
@@ -1,7 +1,4 @@
import { XIcon } from "lucide-react";
import { isElectron } from "../env";
import { useStore } from "../store";
import { Button } from "./ui/button";
export default function DiffPanel() {
const { dispatch } = useStore();
@@ -9,18 +6,15 @@ export default function DiffPanel() {
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<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
<button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<XIcon />
</Button>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
+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,10 +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,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -135,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({
@@ -155,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", () => {
@@ -261,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", () => {
@@ -323,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(
[
@@ -393,73 +283,6 @@ describe("deriveWorkLogEntries", () => {
});
});
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 { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
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 {
@@ -78,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;
@@ -105,52 +86,6 @@ function normalizeDetail(value: string | undefined): string | undefined {
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
@@ -193,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),
@@ -227,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));
@@ -245,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",
};
}
@@ -297,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;
@@ -310,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;
@@ -365,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);
@@ -423,7 +316,7 @@ export function deriveWorkLogEntries(
continue;
}
const fromNotification = entryFromNotification(event);
const fromNotification = entryFromNotification(event, turnStartedAt);
if (fromNotification) {
entries.push(fromNotification);
continue;
+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);
}
@@ -1,32 +1,13 @@
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
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 const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export interface ThreadTerminalGroup {
id: string;
terminalIds: string[];
}
export interface ChatImageAttachment {
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
attachments?: ChatAttachment[];
createdAt: string;
streaming: boolean;
}
@@ -45,13 +26,6 @@ export interface Thread {
projectId: string;
title: string;
model: string;
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
@@ -61,7 +35,4 @@ export interface Thread {
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
}
+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,200 +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 };
}
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("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.");
});
});
-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>;
}
-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
}
}
-857
View File
@@ -1,857 +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("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();
});
});
});
-672
View File
@@ -1,672 +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;
/** 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 {
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> {
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> {
await executeGit(input.cwd, ["worktree", "remove", input.path], {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
await executeGit(input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
}
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
const upstreamRef = trimStdout(
await this.gitStdout(
cwd,
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
true,
),
);
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
return;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0) {
return;
}
if (upstreamBranch.length === 0) {
return;
}
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
}
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);
});
-69
View File
@@ -1,69 +0,0 @@
import { assert, describe, it } from "vitest";
import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
describe("server keybindings", () => {
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 && (",
}),
);
});
});
-352
View File
@@ -1,352 +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" };
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+shift+o", command: "chat.new" },
{ 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 = (): KeybindingWhenNode | 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();
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
}
index += 1;
return expressionNode;
}
return null;
};
const parseUnary = (): KeybindingWhenNode | null => {
const token = tokens[index];
if (token?.type === "not") {
index += 1;
const node = parseUnary();
if (!node) return null;
return { type: "not", node };
}
return parsePrimary();
};
const parseAnd = (): KeybindingWhenNode | null => {
let left = parseUnary();
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary();
if (!right) return null;
left = { type: "and", left, right };
}
return left;
};
const parseOr = (): KeybindingWhenNode | null => {
let left = parseAnd();
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd();
if (!right) return null;
left = { type: "or", left, right };
}
return left;
};
const ast = parseOr();
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();
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 <= 256) {
return merged;
}
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
return merged.slice(-256);
}
export function loadResolvedKeybindingsConfig(
logger: KeybindingsLogger,
): ResolvedKeybindingsConfig {
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
const sanitized: ResolvedKeybindingsConfig = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = keybindingRuleSchema.safeParse(entry);
if (result.success) {
const compiled = compileResolvedKeybindingRule(result.data);
if (!compiled) {
invalidEntries += 1;
continue;
}
sanitized.push(compiled);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + sanitized.length;
const merged = mergeWithDefaultKeybindings(sanitized);
if (mergedBeforeCapLength > 256) {
logger.warn("truncating merged keybindings config to max entries", {
path: configPath,
maxEntries: 256,
});
}
return merged;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
});
}
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
-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();
});
}
-172
View File
@@ -1,172 +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,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
} from "@t3tools/contracts";
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 }));
}
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 }, created: false };
}
const now = new Date().toISOString();
const project: ProjectRecord = {
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
createdAt: now,
updatedAt: now,
};
this.projects = [project, ...this.projects];
this.persist();
return { project: { ...project }, 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();
}
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),
};
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 ||
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);
}
}
-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();
});
});
-130
View File
@@ -1,130 +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;
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, [], {
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);
}
}
-469
View File
@@ -1,469 +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("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();
}
});
});
-972
View File
@@ -1,972 +0,0 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type TerminalClearInput,
type TerminalCloseInput,
type TerminalEvent,
type TerminalOpenInput,
type TerminalResizeInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalWriteInput,
terminalClearInputSchema,
terminalCloseInputSchema,
terminalOpenInputSchema,
terminalResizeInputSchema,
terminalWriteInputSchema,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
import { runProcess } from "./processRunner";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
export interface TerminalManagerEvents {
event: [event: TerminalEvent];
}
export interface TerminalManagerOptions {
logsDir?: string;
historyLineLimit?: number;
ptyAdapter?: PtyAdapter;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessPollIntervalMs?: number;
}
interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
status: TerminalSessionStatus;
pid: number | null;
history: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
cols: number;
rows: number;
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
}
function defaultShellResolver(): string {
if (process.platform === "win32") {
return process.env.ComSpec ?? "cmd.exe";
}
return process.env.SHELL ?? "bash";
}
function normalizeShellCommand(value: string | undefined): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (process.platform === "win32") {
return trimmed;
}
const firstToken = trimmed.split(/\s+/g)[0]?.trim();
if (!firstToken) return null;
return firstToken.replace(/^['"]|['"]$/g, "");
}
function uniqueShells(shells: Array<string | null>): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const shell of shells) {
if (!shell || shell.length === 0) continue;
if (seen.has(shell)) continue;
seen.add(shell);
ordered.push(shell);
}
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver());
if (process.platform === "win32") {
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
}
return uniqueShells([
requested,
normalizeShellCommand(process.env.SHELL),
"/bin/zsh",
"/bin/bash",
"/bin/sh",
"zsh",
"bash",
"sh",
]);
}
function isRetryableShellSpawnError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const message = error.message.toLowerCase();
return (
message.includes("posix_spawnp failed") ||
message.includes("enoent") ||
message.includes("not found") ||
message.includes("file not found") ||
message.includes("no such file")
);
}
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
try {
const result = await runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", command],
{
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
},
);
return result.code === 0;
} catch {
return false;
}
}
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
try {
const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
});
if (pgrepResult.code === 0) {
return pgrepResult.stdout.trim().length > 0;
}
if (pgrepResult.code === 1) {
return false;
}
} catch {
// Fall back to ps when pgrep is unavailable.
}
try {
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
});
if (psResult.code !== 0) {
return false;
}
for (const line of psResult.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
return true;
}
}
return false;
} catch {
return false;
}
}
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (process.platform === "win32") {
return checkWindowsSubprocessActivity(terminalPid);
}
return checkPosixSubprocessActivity(terminalPid);
}
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
const lines = history.split("\n");
if (hasTrailingNewline) {
lines.pop();
}
if (lines.length <= maxLines) return history;
const capped = lines.slice(lines.length - maxLines).join("\n");
return hasTrailingNewline ? `${capped}\n` : capped;
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function toSafeThreadId(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
}
function toSafeTerminalId(terminalId: string): string {
return Buffer.from(terminalId, "utf8").toString("base64url");
}
function toSessionKey(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
function shouldExcludeTerminalEnvKey(key: string): boolean {
const normalizedKey = key.toUpperCase();
if (normalizedKey.startsWith("T3CODE_")) {
return true;
}
if (normalizedKey.startsWith("VITE_")) {
return true;
}
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
}
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const spawnEnv: NodeJS.ProcessEnv = {};
for (const [key, value] of Object.entries(baseEnv)) {
if (value === undefined) continue;
if (shouldExcludeTerminalEnvKey(key)) continue;
spawnEnv[key] = value;
}
return spawnEnv;
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string;
private readonly historyLineLimit: number;
private readonly ptyAdapter: PtyAdapter;
private readonly shellResolver: () => string;
private readonly persistQueues = new Map<string, Promise<void>>();
private readonly persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly pendingPersistHistory = new Map<string, string>();
private readonly threadLocks = new Map<string, Promise<void>>();
private readonly persistDebounceMs: number;
private readonly subprocessChecker: TerminalSubprocessChecker;
private readonly subprocessPollIntervalMs: number;
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
private subprocessPollInFlight = false;
private readonly logger = createLogger("terminal");
constructor(options: TerminalManagerOptions = {}) {
super();
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
this.shellResolver = options.shellResolver ?? defaultShellResolver;
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
this.subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
fs.mkdirSync(this.logsDir, { recursive: true });
}
async open(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const input = terminalOpenInputSchema.parse(raw);
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
const existing = this.sessions.get(sessionKey);
if (!existing) {
await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId, input.terminalId);
const session: TerminalSessionState = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
history,
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, session);
this.startSession(session, input, "started");
return this.snapshot(session);
}
if (existing.cwd !== input.cwd) {
this.stopProcess(existing);
existing.cwd = input.cwd;
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
}
if (!existing.process) {
this.startSession(existing, input, "started");
return this.snapshot(existing);
}
if (existing.cols !== input.cols || existing.rows !== input.rows) {
existing.cols = input.cols;
existing.rows = input.rows;
existing.process.resize(input.cols, input.rows);
existing.updatedAt = new Date().toISOString();
}
return this.snapshot(existing);
});
}
async write(raw: TerminalWriteInput): Promise<void> {
const input = terminalWriteInputSchema.parse(raw);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.process.write(input.data);
}
async resize(raw: TerminalResizeInput): Promise<void> {
const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.cols = input.cols;
session.rows = input.rows;
session.updatedAt = new Date().toISOString();
session.process.resize(input.cols, input.rows);
}
async clear(raw: TerminalClearInput): Promise<void> {
const input = terminalClearInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
type: "cleared",
threadId: input.threadId,
terminalId: input.terminalId,
createdAt: new Date().toISOString(),
});
});
}
async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const input = terminalOpenInputSchema.parse(raw);
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
if (!session) {
session = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
}
session.history = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.startSession(session, input, "restarted");
return this.snapshot(session);
});
}
async close(raw: TerminalCloseInput): Promise<void> {
const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
if (input.terminalId) {
await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
return;
}
const threadSessions = this.sessionsForThread(input.threadId);
for (const session of threadSessions) {
this.stopProcess(session);
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
}
await Promise.all(
threadSessions.map((session) =>
this.flushPersistQueue(session.threadId, session.terminalId),
),
);
if (input.deleteHistory) {
await this.deleteAllHistoryForThread(input.threadId);
}
this.updateSubprocessPollingState();
});
}
dispose(): void {
this.stopSubprocessPolling();
const sessions = [...this.sessions.values()];
this.sessions.clear();
for (const session of sessions) {
this.stopProcess(session);
}
for (const timer of this.persistTimers.values()) {
clearTimeout(timer);
}
this.persistTimers.clear();
this.pendingPersistHistory.clear();
this.threadLocks.clear();
this.persistQueues.clear();
}
private startSession(
session: TerminalSessionState,
input: TerminalOpenInput,
eventType: "started" | "restarted",
): void {
this.stopProcess(session);
session.status = "starting";
session.cwd = input.cwd;
session.cols = input.cols;
session.rows = input.rows;
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
session.updatedAt = new Date().toISOString();
let ptyProcess: PtyProcess | null = null;
let startedShell: string | null = null;
try {
const shellCandidates = resolveShellCandidates(this.shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env);
let lastSpawnError: unknown = null;
for (const shell of shellCandidates) {
try {
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: terminalEnv,
});
startedShell = shell;
break;
} catch (error) {
lastSpawnError = error;
if (!isRetryableShellSpawnError(error)) {
throw error;
}
}
}
if (!ptyProcess) {
const detail =
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
const tried =
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
throw new Error(`${detail}.${tried}`.trim());
}
session.process = ptyProcess;
session.pid = ptyProcess.pid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = ptyProcess.onData((data) => {
this.onProcessData(session, data);
});
session.unsubscribeExit = ptyProcess.onExit((event) => {
this.onProcessExit(session, event);
});
this.updateSubprocessPollingState();
this.emitEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: this.snapshot(session),
});
} catch (error) {
if (ptyProcess) {
try {
ptyProcess.kill();
} catch {
// Ignore kill errors during failed startup cleanup.
}
}
session.status = "error";
session.pid = null;
session.process = null;
session.hasRunningSubprocess = false;
session.updatedAt = new Date().toISOString();
this.updateSubprocessPollingState();
const message = error instanceof Error ? error.message : "Terminal start failed";
this.emitEvent({
type: "error",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
message,
});
this.logger.error("failed to start terminal", {
threadId: session.threadId,
terminalId: session.terminalId,
error: message,
...(startedShell ? { shell: startedShell } : {}),
});
}
}
private onProcessData(session: TerminalSessionState, data: string): void {
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
data,
});
}
private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
this.emitEvent({
type: "exited",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
});
this.updateSubprocessPollingState();
}
private stopProcess(session: TerminalSessionState): void {
const process = session.process;
if (!process) return;
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.updatedAt = new Date().toISOString();
try {
process.kill();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn("failed to kill terminal process", {
threadId: session.threadId,
terminalId: session.terminalId,
error: message,
});
}
this.updateSubprocessPollingState();
}
private cleanupProcessHandles(session: TerminalSessionState): void {
session.unsubscribeData?.();
session.unsubscribeData = null;
session.unsubscribeExit?.();
session.unsubscribeExit = null;
}
private queuePersist(threadId: string, terminalId: string, history: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
this.pendingPersistHistory.set(persistenceKey, history);
this.schedulePersist(threadId, terminalId);
}
private async persistHistory(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, history);
}
private enqueuePersistWrite(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
};
const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
const next = previous
.catch(() => undefined)
.then(task)
.catch((error) => {
this.logger.warn("failed to persist terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
});
this.persistQueues.set(persistenceKey, next);
const finalized = next.finally(() => {
if (this.persistQueues.get(persistenceKey) === next) {
this.persistQueues.delete(persistenceKey);
}
if (
this.pendingPersistHistory.has(persistenceKey) &&
!this.persistTimers.has(persistenceKey)
) {
this.schedulePersist(threadId, terminalId);
}
});
void finalized.catch(() => undefined);
return finalized;
}
private schedulePersist(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
if (this.persistTimers.has(persistenceKey)) return;
const timer = setTimeout(() => {
this.persistTimers.delete(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(persistenceKey);
void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}, this.persistDebounceMs);
this.persistTimers.set(persistenceKey, timer);
}
private clearPersistTimer(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
const timer = this.persistTimers.get(persistenceKey);
if (!timer) return;
clearTimeout(timer);
this.persistTimers.delete(persistenceKey);
}
private async readHistory(threadId: string, terminalId: string): Promise<string> {
const nextPath = this.historyPath(threadId, terminalId);
try {
const raw = await fs.promises.readFile(nextPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(nextPath, capped, "utf8");
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;
}
}
if (terminalId !== DEFAULT_TERMINAL_ID) {
return "";
}
const legacyPath = this.legacyHistoryPath(threadId);
try {
const raw = await fs.promises.readFile(legacyPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
// Migrate legacy transcript filename to the terminal-scoped path.
await fs.promises.writeFile(nextPath, capped, "utf8");
try {
await fs.promises.rm(legacyPath, { force: true });
} catch (cleanupError) {
this.logger.warn("failed to remove legacy terminal history", {
threadId,
error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
});
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return "";
}
throw error;
}
}
private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
if (terminalId === DEFAULT_TERMINAL_ID) {
deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
}
try {
await Promise.all(deletions);
} catch (error) {
this.logger.warn("failed to delete terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
while (true) {
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}
const pending = this.persistQueues.get(persistenceKey);
if (!pending) {
return;
}
await pending.catch(() => undefined);
}
}
private updateSubprocessPollingState(): void {
const hasRunningSessions = [...this.sessions.values()].some(
(session) => session.status === "running" && session.pid !== null,
);
if (hasRunningSessions) {
this.ensureSubprocessPolling();
return;
}
this.stopSubprocessPolling();
}
private ensureSubprocessPolling(): void {
if (this.subprocessPollTimer) return;
this.subprocessPollTimer = setInterval(() => {
void this.pollSubprocessActivity();
}, this.subprocessPollIntervalMs);
this.subprocessPollTimer.unref?.();
void this.pollSubprocessActivity();
}
private stopSubprocessPolling(): void {
if (!this.subprocessPollTimer) return;
clearInterval(this.subprocessPollTimer);
this.subprocessPollTimer = null;
}
private async pollSubprocessActivity(): Promise<void> {
if (this.subprocessPollInFlight) return;
const runningSessions = [...this.sessions.values()].filter(
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" && Number.isInteger(session.pid),
);
if (runningSessions.length === 0) {
this.stopSubprocessPolling();
return;
}
this.subprocessPollInFlight = true;
try {
await Promise.all(
runningSessions.map(async (session) => {
const terminalPid = session.pid;
let hasRunningSubprocess = false;
try {
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
} catch (error) {
this.logger.warn("failed to check terminal subprocess activity", {
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid,
error: error instanceof Error ? error.message : String(error),
});
return;
}
const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
return;
}
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
return;
}
liveSession.hasRunningSubprocess = hasRunningSubprocess;
liveSession.updatedAt = new Date().toISOString();
this.emitEvent({
type: "activity",
threadId: liveSession.threadId,
terminalId: liveSession.terminalId,
createdAt: new Date().toISOString(),
hasRunningSubprocess,
});
}),
);
} finally {
this.subprocessPollInFlight = false;
}
}
private async assertValidCwd(cwd: string): Promise<void> {
let stats: fs.Stats;
try {
stats = await fs.promises.stat(cwd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
}
throw error;
}
if (!stats.isDirectory()) {
throw new Error(`Terminal cwd is not a directory: ${cwd}`);
}
}
private async closeSession(
threadId: string,
terminalId: string,
deleteHistory: boolean,
): Promise<void> {
const key = toSessionKey(threadId, terminalId);
const session = this.sessions.get(key);
if (session) {
this.stopProcess(session);
this.sessions.delete(key);
}
this.updateSubprocessPollingState();
await this.flushPersistQueue(threadId, terminalId);
if (deleteHistory) {
await this.deleteHistory(threadId, terminalId);
}
}
private sessionsForThread(threadId: string): TerminalSessionState[] {
return [...this.sessions.values()].filter((session) => session.threadId === threadId);
}
private async deleteAllHistoryForThread(threadId: string): Promise<void> {
const threadPrefix = `${toSafeThreadId(threadId)}_`;
try {
const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
const removals = entries
.filter((entry) => entry.isFile())
.map((entry) => entry.name)
.filter(
(name) =>
name === `${toSafeThreadId(threadId)}.log` ||
name === `${legacySafeThreadId(threadId)}.log` ||
name.startsWith(threadPrefix),
)
.map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
await Promise.all(removals);
} catch (error) {
this.logger.warn("failed to delete terminal histories for thread", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private requireSession(threadId: string, terminalId: string): TerminalSessionState {
const session = this.sessions.get(toSessionKey(threadId, terminalId));
if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
}
return session;
}
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
status: session.status,
pid: session.pid,
history: session.history,
exitCode: session.exitCode,
exitSignal: session.exitSignal,
updatedAt: session.updatedAt,
};
}
private emitEvent(event: TerminalEvent): void {
this.emit("event", event);
}
private historyPath(threadId: string, terminalId: string): string {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
return path.join(this.logsDir, `${threadPart}.log`);
}
return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
}
private legacyHistoryPath(threadId: string): string {
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
}
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
let release: () => void = () => {};
const current = new Promise<void>((resolve) => {
release = resolve;
});
this.threadLocks.set(threadId, current);
await previous.catch(() => undefined);
try {
return await task();
} finally {
release();
if (this.threadLocks.get(threadId) === current) {
this.threadLocks.delete(threadId);
}
}
}
}
-937
View File
@@ -1,937 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { EventEmitter } from "node:events";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import {
DEFAULT_TERMINAL_ID,
WS_CHANNELS,
WS_METHODS,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
import type {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
TerminalWriteInput,
} from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager";
interface PendingMessages {
queue: unknown[];
waiters: Array<(message: unknown) => void>;
}
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 4242,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "started",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async write(input: TerminalWriteInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const existing = this.sessions.get(this.key(input.threadId, terminalId));
if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`);
}
queueMicrotask(() => {
this.emit("event", {
type: "output",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
data: input.data,
});
});
}
async resize(_input: TerminalResizeInput): Promise<void> {}
async clear(input: TerminalClearInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
queueMicrotask(() => {
this.emit("event", {
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
});
});
}
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 5252,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "restarted",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async close(input: TerminalCloseInput): Promise<void> {
if (input.terminalId) {
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
}
}
dispose(): void {}
}
function connectWs(port: number, token?: string): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const pending: PendingMessages = { queue: [], waiters: [] };
pendingBySocket.set(ws, pending);
ws.on("message", (raw) => {
const parsed = JSON.parse(String(raw));
const waiter = pending.waiters.shift();
if (waiter) {
waiter(parsed);
return;
}
pending.queue.push(parsed);
});
ws.once("open", () => resolve(ws));
ws.once("error", () => reject(new Error("WebSocket connection failed")));
});
}
function waitForMessage(ws: WebSocket): Promise<unknown> {
const pending = pendingBySocket.get(ws);
if (!pending) {
return Promise.reject(new Error("WebSocket not initialized"));
}
const queued = pending.queue.shift();
if (queued !== undefined) {
return Promise.resolve(queued);
}
return new Promise((resolve) => {
pending.waiters.push(resolve);
});
}
async function sendRequest(ws: WebSocket, method: string, params?: unknown): Promise<WsResponse> {
const id = crypto.randomUUID();
const message = JSON.stringify({ id, method, ...(params !== undefined ? { params } : {}) });
ws.send(message);
// Wait for response with matching id
while (true) {
const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
if (parsed.id === id) {
return parsed as WsResponse;
}
}
}
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
const resolved: ResolvedKeybindingsConfig = [];
for (const binding of bindings) {
const compiled = compileResolvedKeybindingRule(binding);
if (!compiled) {
throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
}
resolved.push(compiled);
}
return resolved;
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
return DEFAULT_RESOLVED_KEYBINDINGS;
}
const overriddenCommands = new Set(custom.map((binding) => binding.command));
const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
(binding) => !overriddenCommands.has(binding.command),
);
return compileKeybindings([...retainedDefaults, ...custom].slice(-256));
}
describe("WebSocket Server", () => {
let server: ReturnType<typeof createServer> | null = null;
const connections: WebSocket[] = [];
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function createTestServer(
options: {
cwd?: string;
devUrl?: string;
authToken?: string;
stateDir?: string;
gitManager?: {
status: (input: { cwd: string }) => Promise<unknown>;
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
};
terminalManager?: TerminalManager;
} = {},
): ReturnType<typeof createServer> {
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
});
}
afterEach(async () => {
for (const ws of connections) {
ws.close();
}
connections.length = 0;
if (server) {
await server.stop();
}
server = null;
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
vi.restoreAllMocks();
});
it("sends welcome message on connect", async () => {
server = createTestServer({ cwd: "/test/project" });
// Get the actual port after listen
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const ws = await connectWs(port);
connections.push(ws);
const message = (await waitForMessage(ws)) as WsPush;
expect(message.type).toBe("push");
expect(message.channel).toBe(WS_CHANNELS.serverWelcome);
expect(message.data).toEqual({
cwd: "/test/project",
projectName: "project",
});
});
it("logs outbound websocket push events in dev mode", async () => {
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {
// Keep test output clean while verifying websocket logs.
});
server = createTestServer({
cwd: "/test/project",
devUrl: "http://localhost:5173",
});
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
expect(
logSpy.mock.calls.some(([message]) => {
if (typeof message !== "string") return false;
return (
message.includes("[ws]") &&
message.includes("outgoing push") &&
message.includes(`channel="${WS_CHANNELS.serverWelcome}"`)
);
}),
).toBe(true);
});
it("responds to server.getConfig", async () => {
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome message
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
});
it("reads keybindings from ~/.t3/keybindings.json", async () => {
const fakeHome = makeTempDir("t3code-home-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([
{ key: "cmd+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([
{ key: "cmd+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
]),
});
});
it("warns and ignores invalid keybinding entries", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-entry-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+z", command: "invalid.command", when: "terminalFocus" },
]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]),
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring invalid keybinding entries"),
),
).toBe(true);
});
it("warns and ignores keybindings with malformed when expressions", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-when-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring invalid keybinding entries"),
),
).toBe(true);
});
it("reads keybindings once at startup and caches the resolved config", async () => {
const fakeHome = makeTempDir("t3code-home-cached-config-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const keybindingsPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(firstResponse.error).toBeUndefined();
expect(firstResponse.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]),
});
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]),
"utf8",
);
const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(secondResponse.error).toBeUndefined();
expect(secondResponse.result).toEqual(firstResponse.result);
});
it("warns and ignores unsupported keybindings config format", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify({ "terminal.toggle": "mod+j" }),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("unsupported format; expected array"),
),
).toBe(true);
});
it("warns and ignores malformed keybindings config files", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring malformed keybindings config"),
),
).toBe(true);
});
it("returns error for unknown methods", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, "nonexistent.method");
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Unknown method");
});
it("responds to providers.listSessions with empty array", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.providersListSessions);
expect(response.error).toBeUndefined();
expect(response.result).toEqual([]);
});
it("routes terminal RPC methods and broadcasts terminal events", async () => {
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
const terminalManager = new MockTerminalManager();
server = createTestServer({
cwd: "/test",
terminalManager: terminalManager as unknown as TerminalManager,
});
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const open = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "thread-1",
cwd,
cols: 100,
rows: 24,
});
expect(open.error).toBeUndefined();
expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1");
expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID);
const write = await sendRequest(ws, WS_METHODS.terminalWrite, {
threadId: "thread-1",
data: "echo hello\n",
});
expect(write.error).toBeUndefined();
const resize = await sendRequest(ws, WS_METHODS.terminalResize, {
threadId: "thread-1",
cols: 120,
rows: 30,
});
expect(resize.error).toBeUndefined();
const clear = await sendRequest(ws, WS_METHODS.terminalClear, {
threadId: "thread-1",
});
expect(clear.error).toBeUndefined();
const restart = await sendRequest(ws, WS_METHODS.terminalRestart, {
threadId: "thread-1",
cwd,
cols: 120,
rows: 30,
});
expect(restart.error).toBeUndefined();
const close = await sendRequest(ws, WS_METHODS.terminalClose, {
threadId: "thread-1",
deleteHistory: true,
});
expect(close.error).toBeUndefined();
const manualEvent: TerminalEvent = {
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "manual test output\n",
};
terminalManager.emit("event", manualEvent);
const push = (await waitForMessage(ws)) as WsPush;
expect(push.type).toBe("push");
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
expect((push.data as TerminalEvent).type).toBe("output");
});
it("detaches terminal event listener on stop for injected manager", async () => {
const terminalManager = new MockTerminalManager();
server = createTestServer({
cwd: "/test",
terminalManager: terminalManager as unknown as TerminalManager,
});
await server.start();
expect(terminalManager.listenerCount("event")).toBe(1);
await server.stop();
server = null;
expect(terminalManager.listenerCount("event")).toBe(0);
});
it("returns validation errors for invalid terminal open params", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "",
cwd: "",
cols: 1,
rows: 1,
});
expect(response.error).toBeDefined();
});
it("handles invalid JSON gracefully", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
// Send garbage
ws.send("not json at all");
const response = (await waitForMessage(ws)) as WsResponse;
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Invalid request format");
});
it("supports projects list/add/dedupe/remove", async () => {
const stateDir = makeTempDir("t3code-ws-projects-state-");
const firstProjectCwd = makeTempDir("t3code-ws-project-a-");
server = createTestServer({ stateDir, cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const emptyList = await sendRequest(ws, WS_METHODS.projectsList);
expect(emptyList.error).toBeUndefined();
expect(emptyList.result).toEqual([]);
const created = await sendRequest(ws, WS_METHODS.projectsAdd, {
cwd: firstProjectCwd,
});
expect(created.error).toBeUndefined();
expect((created.result as { created: boolean }).created).toBe(true);
const duplicate = await sendRequest(ws, WS_METHODS.projectsAdd, {
cwd: firstProjectCwd,
});
expect(duplicate.error).toBeUndefined();
expect((duplicate.result as { created: boolean }).created).toBe(false);
const listed = await sendRequest(ws, WS_METHODS.projectsList);
expect(listed.error).toBeUndefined();
const listedProjects = listed.result as Array<{ id: string; cwd: string }>;
expect(listedProjects).toHaveLength(1);
const projectId = listedProjects[0]?.id;
expect(projectId).toBeTruthy();
if (!projectId) return;
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
id: projectId,
});
expect(removed.error).toBeUndefined();
const afterRemove = await sendRequest(ws, WS_METHODS.projectsList);
expect(afterRemove.error).toBeUndefined();
expect(afterRemove.result).toEqual([]);
});
it("supports git methods over websocket", async () => {
const repoCwd = makeTempDir("t3code-ws-git-project-");
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const beforeInit = await sendRequest(ws, WS_METHODS.gitListBranches, { cwd: repoCwd });
expect(beforeInit.error).toBeUndefined();
expect(beforeInit.result).toEqual({ branches: [], isRepo: false });
const initResponse = await sendRequest(ws, WS_METHODS.gitInit, { cwd: repoCwd });
expect(initResponse.error).toBeUndefined();
const afterInit = await sendRequest(ws, WS_METHODS.gitListBranches, {
cwd: repoCwd,
});
expect(afterInit.error).toBeUndefined();
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
const pullResponse = await sendRequest(ws, WS_METHODS.gitPull, { cwd: repoCwd });
expect(pullResponse.result).toBeUndefined();
expect(pullResponse.error?.message).toBeDefined();
expect(pullResponse.error?.message).not.toContain("Unknown method");
});
it("responds to git.status via the git manager", async () => {
const gitManager = {
status: vi.fn().mockResolvedValue({
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: {
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
insertions: 7,
deletions: 2,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
}),
runStackedAction: vi.fn(),
};
server = createTestServer({ cwd: "/test", gitManager });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.gitStatus, {
cwd: "/test",
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: {
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
insertions: 7,
deletions: 2,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
});
expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" });
});
it("returns errors from git.runStackedAction", async () => {
const gitManager = {
status: vi.fn(),
runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),
};
server = createTestServer({ cwd: "/test", gitManager });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
cwd: "/test",
action: "commit_push",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(gitManager.runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit_push",
});
});
it("prunes missing projects on startup", async () => {
const stateDir = makeTempDir("t3code-ws-prune-state-");
const existing = makeTempDir("t3code-ws-existing-project-");
const missing = path.join(stateDir, "definitely-missing");
const now = new Date().toISOString();
const projectsFile = path.join(stateDir, "projects.json");
fs.writeFileSync(
projectsFile,
JSON.stringify(
{
version: 1,
projects: [
{
id: "project-existing",
cwd: existing,
name: "existing",
createdAt: now,
updatedAt: now,
},
{
id: "project-missing",
cwd: missing,
name: "missing",
createdAt: now,
updatedAt: now,
},
],
},
null,
2,
),
);
server = createTestServer({ stateDir, cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsList);
expect(response.error).toBeUndefined();
const listed = response.result as Array<{ id: string }>;
expect(listed).toHaveLength(1);
expect(listed[0]?.id).toBe("project-existing");
});
it("rejects websocket connections without a valid auth token", async () => {
server = createTestServer({ cwd: "/test", authToken: "secret-token" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
const authorizedWs = await connectWs(port, "secret-token");
connections.push(authorizedWs);
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
});
});
-488
View File
@@ -1,488 +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 } from "./keybindings";
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);
const 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.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.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,
};
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>
-215
View File
@@ -1,215 +0,0 @@
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
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 { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
import { invalidateGitQueries } from "./lib/gitReactQuery";
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,
},
});
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: [],
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,
})),
});
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();
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 />
{state.diffOpen && <DiffPanel />}
</div>
);
}
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ToastProvider>
<AnchoredToastProvider>
<Layout />
</AnchoredToastProvider>
</ToastProvider>
</StoreProvider>
</QueryClientProvider>
);
}
-266
View File
@@ -1,266 +0,0 @@
import type { GitBranch } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useNativeApi } from "../hooks/useNativeApi";
import {
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { useStore } from "../store";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
interface BranchToolbarProps {
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
}
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(api, branchCwd));
const branches = branchesQuery.data?.branches ?? [];
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems =
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames;
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation({
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
setIsBranchMenuOpen(true);
},
});
const createBranchMutation = useMutation({
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
onError: (error) =>
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
});
// ── Effects ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
if (!activeThreadId || activeWorktreePath) return;
const current = queryBranches?.find((branch) => branch.current);
if (!current) return;
if (current.name === activeThreadBranch) return;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: current.name,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
setBranchQuery("");
}, [isBranchMenuOpen]);
// ── Helpers ───────────────────────────────────────────────────────────
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = activeThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
const selectBranch = (branch: GitBranch) => {
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
return;
}
// If the branch already lives in a worktree, redirect there instead of
// trying to checkout (which git would reject with "already used by worktree").
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
setThreadError(null);
// Main worktree → switch back to local (project cwd, worktreePath=null).
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
return;
}
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
},
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setIsBranchMenuOpen(false);
},
});
};
if (!activeThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
<div className="flex items-center gap-2">
{envLocked || activeWorktreePath ? (
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? "Worktree" : "Local"}
</span>
) : (
<Button
type="button"
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
>
{envMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={activeThread.branch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList className="max-h-56">
{(itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</div>
</ComboboxItem>
);
}}
</ComboboxList>
</ComboboxPopup>
</Combobox>
</div>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,727 +0,0 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { assert, describe, it } from "vitest";
import {
buildGitActionProgressStages,
buildMenuItems,
requiresDefaultBranchConfirmation,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
return {
branch: "feature/test",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
openPr: null,
...overrides,
};
}
describe("when: branch is clean and has an open PR", () => {
it("resolveQuickAction opens the existing PR", () => {
const quick = resolveQuickAction(
status({
openPr: {
number: 10,
title: "Open PR",
url: "https://example.com/pr/10",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepInclude(quick, { kind: "open_pr", label: "Open PR", disabled: false });
});
it("buildMenuItems disables commit/push and enables open PR", () => {
const items = buildMenuItems(
status({
openPr: {
number: 11,
title: "Existing PR",
url: "https://example.com/pr/11",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Open PR",
disabled: false,
icon: "pr",
kind: "open_pr",
},
]);
});
});
describe("when: actions are busy", () => {
it("resolveQuickAction returns running disabled state", () => {
const quick = resolveQuickAction(status(), true);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
disabled: true,
hint: "Git action in progress.",
});
});
it("buildMenuItems disables all actions", () => {
const items = buildMenuItems(status(), true);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: git status is unavailable", () => {
it("resolveQuickAction returns unavailable disabled state", () => {
const quick = resolveQuickAction(null, false);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
disabled: true,
hint: "Git status is unavailable.",
});
});
it("buildMenuItems returns no menu items", () => {
const items = buildMenuItems(null, false);
assert.deepEqual(items, []);
});
});
describe("when: branch is clean, ahead, and has an open PR", () => {
it("resolveQuickAction prefers push", () => {
const quick = resolveQuickAction(
status({
aheadCount: 3,
openPr: {
number: 13,
title: "Open PR",
url: "https://example.com/pr/13",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepInclude(quick, { kind: "run_action", action: "commit_push", label: "Push" });
});
it("buildMenuItems enables push and keeps open PR available", () => {
const items = buildMenuItems(
status({
aheadCount: 2,
openPr: {
number: 12,
title: "Existing PR",
url: "https://example.com/pr/12",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Open PR",
disabled: false,
icon: "pr",
kind: "open_pr",
},
]);
});
});
describe("when: branch is clean, ahead, and has no open PR", () => {
it("resolveQuickAction pushes and creates a PR", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Push & create PR",
});
});
it("buildMenuItems enables push and create PR, with commit disabled", () => {
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: false,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: branch is clean, up to date, and has no open PR", () => {
it("resolveQuickAction returns disabled no-action state", () => {
const quick = resolveQuickAction(
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
false,
);
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
});
it("buildMenuItems disables commit, push, and create PR", () => {
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: branch is behind upstream", () => {
it("resolveQuickAction returns pull", () => {
const quick = resolveQuickAction(status({ behindCount: 2 }), false);
assert.deepInclude(quick, { kind: "run_pull", label: "Pull", disabled: false });
});
it("buildMenuItems disables push and create PR", () => {
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: branch has diverged from upstream", () => {
it("resolveQuickAction returns a disabled sync hint", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
assert.deepEqual(quick, {
label: "Sync branch",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
});
});
});
describe("when: working tree has local changes", () => {
it("resolveQuickAction returns commit, push, and create PR", () => {
const quick = resolveQuickAction(status({ hasWorkingTreeChanges: true }), false);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Commit, push & create PR",
});
});
it("resolveQuickAction returns commit and push when open PR exists", () => {
const quick = resolveQuickAction(
status({
hasWorkingTreeChanges: true,
openPr: {
number: 16,
title: "Existing PR",
url: "https://example.com/pr/16",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Commit & push",
});
});
it("buildMenuItems enables commit and disables push and PR", () => {
const items = buildMenuItems(status({ hasWorkingTreeChanges: true }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: false,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: on default branch without open PR", () => {
it("resolveQuickAction returns commit and push when local changes exist", () => {
const quick = resolveQuickAction(
status({ branch: "main", hasWorkingTreeChanges: true }),
false,
true,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Commit & push",
disabled: false,
});
});
it("resolveQuickAction returns push when branch is ahead", () => {
const quick = resolveQuickAction(
status({ branch: "main", aheadCount: 2, openPr: null }),
false,
true,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Push",
disabled: false,
});
});
});
describe("when: working tree has local changes and branch is behind upstream", () => {
it("resolveQuickAction still prefers commit, push, and create PR", () => {
const quick = resolveQuickAction(
status({ hasWorkingTreeChanges: true, behindCount: 1 }),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Commit, push & create PR",
});
});
it("buildMenuItems enables commit and keeps push and PR disabled", () => {
const items = buildMenuItems(status({ hasWorkingTreeChanges: true, behindCount: 2 }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: false,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: HEAD is detached and there are no local changes", () => {
it("resolveQuickAction shows detached head hint", () => {
const quick = resolveQuickAction(
status({ branch: null, hasWorkingTreeChanges: false, hasUpstream: false }),
false,
);
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
});
it("buildMenuItems keeps commit, push, and PR disabled", () => {
const items = buildMenuItems(status({ branch: null, hasWorkingTreeChanges: false }), false);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: branch has no upstream configured", () => {
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
const quick = resolveQuickAction(
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
disabled: true,
});
});
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
aheadCount: 0,
openPr: {
number: 14,
title: "Existing PR",
url: "https://example.com/pr/14",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
disabled: true,
});
});
it("resolveQuickAction runs push when clean, no upstream, and local commits are ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
aheadCount: 1,
openPr: {
number: 15,
title: "Existing PR",
url: "https://example.com/pr/15",
baseBranch: "main",
headBranch: "feature/test",
},
}),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Push",
disabled: false,
});
});
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("requiresDefaultBranchConfirmation", () => {
it("requires confirmation only for push actions on default branch", () => {
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
assert.isFalse(requiresDefaultBranchConfirmation("commit_push", false));
});
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
const stages = buildGitActionProgressStages({
action: "commit_push",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
});
it("includes commit stages for commit+push when working tree is dirty", () => {
const stages = buildGitActionProgressStages({
action: "commit_push",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, [
"Generating commit message...",
"Committing...",
"Pushing to origin/feature/test...",
]);
});
});
describe("summarizeGitResult", () => {
it("returns commit-focused toast for commit action", () => {
const result = summarizeGitResult({
action: "commit",
commit: {
status: "created",
commitSha: "0123456789abcdef",
subject: "feat: add optimistic UI for git action button",
},
push: { status: "skipped_not_requested" },
pr: { status: "skipped_not_requested" },
});
assert.deepEqual(result, {
title: "Committed 0123456",
description: "feat: add optimistic UI for git action button",
});
});
it("returns push-focused toast for push action", () => {
const result = summarizeGitResult({
action: "commit_push",
commit: {
status: "created",
commitSha: "abcdef0123456789",
subject: "fix: tighten quick action tooltip hover handling",
},
push: {
status: "pushed",
branch: "foo",
upstreamBranch: "origin/foo",
},
pr: { status: "skipped_not_requested" },
});
assert.deepEqual(result, {
title: "Pushed abcdef0 to origin/foo",
description: "fix: tighten quick action tooltip hover handling",
});
});
it("returns PR-focused toast for created PR action", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: ship github shortcuts",
},
push: {
status: "pushed",
branch: "foo",
},
pr: {
status: "created",
number: 42,
title: "feat: ship github shortcuts and improve PR CTA in success toast",
},
});
assert.deepEqual(result, {
title: "Created PR #42",
description: "feat: ship github shortcuts and improve PR CTA in success toast",
});
});
it("truncates long description text", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "short subject",
},
push: { status: "pushed", branch: "foo" },
pr: {
status: "created",
number: 99,
title:
"feat: this title is intentionally extremely long so we can validate that toast descriptions are truncated with an ellipsis suffix",
},
});
assert.deepEqual(result, {
title: "Created PR #99",
description: "feat: this title is intentionally extremely long so we can validate t...",
});
});
});
@@ -1,254 +0,0 @@
import type {
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
} from "@t3tools/contracts";
export type GitActionIconName = "commit" | "push" | "pr";
export type GitDialogAction = "commit" | "push" | "create_pr";
export interface GitActionMenuItem {
id: "commit" | "push" | "pr";
label: string;
disabled: boolean;
icon: GitActionIconName;
kind: "open_dialog" | "open_pr";
dialogAction?: GitDialogAction;
}
export interface GitQuickAction {
label: string;
disabled: boolean;
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
action?: GitStackedAction;
hint?: string;
}
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
return sha.slice(0, SHORT_SHA_LENGTH);
}
function truncateText(
value: string | undefined,
maxLength = TOAST_DESCRIPTION_MAX,
): string | undefined {
if (!value) return undefined;
if (value.length <= maxLength) return value;
if (maxLength <= 3) return "...".slice(0, maxLength);
return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
}
export function buildGitActionProgressStages(input: {
action: GitStackedAction;
hasCustomCommitMessage: boolean;
hasWorkingTreeChanges: boolean;
forcePushOnly?: boolean;
pushTarget?: string;
}): string[] {
const shouldIncludeCommitStages =
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
const commitStages = !shouldIncludeCommitStages
? []
: input.hasCustomCommitMessage
? ["Committing..."]
: ["Generating commit message...", "Committing..."];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
if (input.action === "commit") {
return commitStages;
}
if (input.action === "commit_push") {
return [...commitStages, pushStage];
}
return [...commitStages, pushStage, "Creating PR..."];
}
export function summarizeGitResult(result: GitRunStackedActionResult): {
title: string;
description?: string;
} {
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
return withDescription(title, truncateText(result.pr.title));
}
if (result.push.status === "pushed") {
const shortSha = shortenSha(result.commit.commitSha);
const branch = result.push.upstreamBranch ?? result.push.branch;
const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
const branchPart = branch ? ` to ${branch}` : "";
return withDescription(
`Pushed${pushedCommitPart}${branchPart}`,
truncateText(result.commit.subject),
);
}
if (result.commit.status === "created") {
const shortSha = shortenSha(result.commit.commitSha);
const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
return withDescription(title, truncateText(result.commit.subject));
}
return { title: "Done" };
}
export function buildMenuItems(
gitStatus: GitStatusResult | null,
isBusy: boolean,
): GitActionMenuItem[] {
if (!gitStatus) return [];
const hasBranch = gitStatus.branch !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.openPr !== null;
const isBehind = gitStatus.behindCount > 0;
const canCommit = !isBusy && hasChanges;
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
const canCreatePr =
!isBusy &&
hasBranch &&
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
gitStatus.hasUpstream &&
!isBehind;
const canOpenPr = !isBusy && hasOpenPr;
return [
{
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: !canPush,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
hasOpenPr
? {
id: "pr",
label: "Open PR",
disabled: !canOpenPr,
icon: "pr",
kind: "open_pr",
}
: {
id: "pr",
label: "Create PR",
disabled: !canCreatePr,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
];
}
export function resolveQuickAction(
gitStatus: GitStatusResult | null,
isBusy: boolean,
isDefaultBranch = false,
): GitQuickAction {
if (isBusy) {
return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
}
if (!gitStatus) {
return {
label: "Commit",
disabled: true,
kind: "show_hint",
hint: "Git status is unavailable.",
};
}
const hasBranch = gitStatus.branch !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.openPr !== null;
const isAhead = gitStatus.aheadCount > 0;
const isBehind = gitStatus.behindCount > 0;
const isDiverged = isAhead && isBehind;
if (!hasBranch) {
return {
label: "Commit",
disabled: true,
kind: "show_hint",
hint: "Create and checkout a branch before pushing or opening a PR.",
};
}
if (hasChanges) {
if (hasOpenPr || isDefaultBranch) {
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Commit, push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
};
}
if (isDiverged) {
return {
label: "Sync branch",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
};
}
if (isBehind) {
return {
label: "Pull",
disabled: false,
kind: "run_pull",
};
}
if (isAhead) {
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
};
}
if (hasOpenPr && gitStatus.hasUpstream) {
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
label: "Commit",
disabled: true,
kind: "show_hint",
hint: "Branch is up to date. No action needed.",
};
}
export function requiresDefaultBranchConfirmation(
action: GitStackedAction,
isDefaultBranch: boolean,
): boolean {
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
}
@@ -1,734 +0,0 @@
import { type GitStatusResult, type GitStackedAction, type NativeApi } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
import {
buildGitActionProgressStages,
buildMenuItems,
type GitActionIconName,
type GitActionMenuItem,
type GitDialogAction,
type GitQuickAction,
requiresDefaultBranchConfirmation,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
import { Button } from "~/components/ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "~/components/ui/dialog";
import { Group, GroupSeparator } from "~/components/ui/group";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { useStore } from "~/store";
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
}
function getMenuActionDisabledReason(
item: GitActionMenuItem,
gitStatus: GitStatusResult | null,
isBusy: boolean,
): string | null {
if (!item.disabled) return null;
if (isBusy) return "Git action in progress.";
if (!gitStatus) return "Git status is unavailable.";
const hasBranch = gitStatus.branch !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.openPr !== null;
const isAhead = gitStatus.aheadCount > 0;
const isBehind = gitStatus.behindCount > 0;
if (item.id === "commit") {
if (!hasChanges) {
return "Worktree is clean. Make changes before committing.";
}
return "Commit is currently unavailable.";
}
if (item.id === "push") {
if (!hasBranch) {
return "Detached HEAD: checkout a branch before pushing.";
}
if (hasChanges) {
return "Commit or stash local changes before pushing.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before pushing.";
}
if (!isAhead) {
return "No local commits to push.";
}
return "Push is currently unavailable.";
}
if (hasOpenPr) {
return "Open PR is currently unavailable.";
}
if (!hasBranch) {
return "Detached HEAD: checkout a branch before creating a PR.";
}
if (hasChanges) {
return "Commit local changes before creating a PR.";
}
if (!isAhead) {
return "No local commits to include in a PR.";
}
if (!gitStatus.hasUpstream) {
return "Set an upstream branch before creating a PR.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before creating a PR.";
}
return "Create PR is currently unavailable.";
}
const DIALOG_TITLE_BY_ACTION = {
commit: "Commit changes",
push: "Push branch",
create_pr: "Create pull request",
};
const DIALOG_DESCRIPTION_BY_ACTION = {
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
push: "Push this branch now.",
create_pr: "Create a pull request using generated title/body content.",
};
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
if (icon === "commit") return <GitCommitIcon />;
if (icon === "push") return <CloudUploadIcon />;
return <GitHubIcon />;
}
function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
const iconClassName = "size-3.5";
if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
return <GitHubIcon className={iconClassName} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
return <InfoIcon className={iconClassName} />;
}
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const { state } = useStore();
const activeThreadId = state.activeThreadId;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const queryClient = useQueryClient();
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(api, gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const initMutation = useMutation(gitInitMutationOptions({ api, cwd: gitCwd, queryClient }));
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ api, cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ api, cwd: gitCwd, queryClient }));
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning),
[gitStatusForActions, isGitActionRunning],
);
const quickAction = useMemo(
() => resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch),
[gitStatusForActions, isDefaultBranch, isGitActionRunning],
);
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[api, gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
data: threadToastData,
});
return;
}
const prUrl = gitStatusForActions?.openPr?.url ?? null;
if (!prUrl) {
toastManager.add({
type: "error",
title: "No open PR found.",
data: threadToastData,
});
return;
}
const promise = api.shell.openExternal(prUrl);
toastManager.promise(promise, {
loading: { title: "Opening PR...", data: threadToastData },
success: { title: "PR opened", data: threadToastData },
error: (err) => ({
title: "Unable to open PR link",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const confirmed = await maybeConfirmPushToDefaultBranch(action);
if (!confirmed) return;
onConfirmed?.();
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
const progressToastId = toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(progressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
data: threadToastData,
});
}, 1100);
const stopProgressUpdates = () => {
clearInterval(stageInterval);
};
const promise = runImmediateGitActionMutation.mutateAsync({
action,
...(commitMessage ? { commitMessage } : {}),
});
try {
const result = await promise;
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
const shouldOfferCreatePrCta =
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
const closeResultToast = () => {
toastManager.close(progressToastId);
};
toastManager.update(progressToastId, {
type: "success",
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: threadToastData,
...(shouldOfferPushCta
? {
actionProps: {
children: "Push",
onClick: () => {
void runGitActionWithToast({
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
});
},
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "Open PR",
onClick: () => {
closeResultToast();
void api?.shell.openExternal(prUrl);
},
},
}
: shouldOfferCreatePrCta
? {
actionProps: {
children: "Create PR",
onClick: () => {
closeResultToast();
setActiveDialogAction("create_pr");
},
},
}
: {}),
});
} catch (err) {
stopProgressUpdates();
toastManager.update(progressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
});
}
},
[
api,
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.openPr?.url,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setActiveDialogAction,
threadToastData,
],
);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
return;
}
if (quickAction.kind === "run_pull") {
const promise = pullMutation.mutateAsync();
toastManager.promise(promise, {
loading: { title: "Pulling...", data: threadToastData },
success: (result) => ({
title: result.status === "pulled" ? "Pulled" : "Already up to date",
description:
result.status === "pulled"
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
: `${result.branch} is already synchronized.`,
data: threadToastData,
}),
error: (err) => ({
title: "Pull failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
return;
}
if (quickAction.kind === "show_hint") {
toastManager.add({
type: "info",
title: quickAction.label,
description: quickAction.hint,
data: threadToastData,
});
return;
}
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction) {
setActiveDialogAction(item.dialogAction);
}
},
[openExistingPr, runGitActionWithToast],
);
const runDialogAction = useCallback(() => {
if (!activeDialogAction) return;
const action: GitStackedAction =
activeDialogAction === "commit"
? "commit"
: activeDialogAction === "push"
? "commit_push"
: "commit_push_pr";
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
const forcePushOnlyProgress = activeDialogAction === "push";
setActiveDialogAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
});
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
const openChangedFileInEditor = useCallback(
(filePath: string) => {
if (!api || !gitCwd) {
toastManager.add({
type: "error",
title: "Editor opening is unavailable.",
data: threadToastData,
});
return;
}
const target = resolvePathLinkTarget(filePath, gitCwd);
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[api, gitCwd, threadToastData],
);
if (!gitCwd) return null;
return (
<>
{!isRepo ? (
<Button
variant="outline"
size="xs"
disabled={initMutation.isPending}
onClick={() => initMutation.mutate()}
>
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
</Button>
) : (
<Group aria-label="Git actions">
{quickActionDisabledReason ? (
<Popover>
<PopoverTrigger
openOnHover
render={
<Button
aria-disabled="true"
className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
size="xs"
variant="outline"
/>
}
>
<GitQuickActionIcon quickAction={quickAction} />
<span className="ml-0.5">{quickAction.label}</span>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="start">
{quickActionDisabledReason}
</PopoverPopup>
</Popover>
) : (
<Button
variant="outline"
size="xs"
disabled={isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
<GitQuickActionIcon quickAction={quickAction} />
<span className="ml-0.5">{quickAction.label}</span>
</Button>
)}
<GroupSeparator />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
}}
>
<MenuTrigger
render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
disabled={isGitActionRunning}
>
<ChevronDownIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end" className="w-full">
{gitActionMenuItems.map((item) => {
const disabledReason = getMenuActionDisabledReason(
item,
gitStatusForActions,
isGitActionRunning,
);
if (item.disabled && disabledReason) {
return (
<Popover key={`${item.id}-${item.label}`}>
<PopoverTrigger
openOnHover
nativeButton={false}
render={<span className="block w-max cursor-not-allowed" />}
>
<MenuItem className="w-full" disabled>
<GitActionItemIcon icon={item.icon} />
{item.label}
</MenuItem>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="left" align="center">
{disabledReason}
</PopoverPopup>
</Popover>
);
}
return (
<MenuItem
key={`${item.id}-${item.label}`}
disabled={item.disabled}
onClick={() => {
openDialogForMenuItem(item);
}}
>
<GitActionItemIcon icon={item.icon} />
{item.label}
</MenuItem>
);
})}
{gitStatusForActions?.branch === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and checkout a branch to enable push and PR actions.
</p>
)}
{gitStatusForActions &&
gitStatusForActions.branch !== null &&
!gitStatusForActions.hasWorkingTreeChanges &&
gitStatusForActions.behindCount > 0 &&
gitStatusForActions.aheadCount === 0 && (
<p className="px-2 py-1.5 text-xs text-warning">
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
</MenuPopup>
</Menu>
</Group>
)}
<Dialog
open={activeDialogAction !== null}
onOpenChange={(open) => {
if (!open) {
setActiveDialogAction(null);
setDialogCommitMessage("");
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
<DialogDescription>
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
</span>
</>
)}
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
{!gitStatusForActions || gitStatusForActions.workingTree.files.length === 0 ? (
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<ScrollArea className="h-44 rounded-md border border-input bg-background">
<div className="space-y-1 p-1">
{gitStatusForActions.workingTree.files.map((file) => (
<button
type="button"
key={file.path}
className="flex w-full items-center justify-between gap-3 rounded-md px-2 py-1 font-mono text-left transition-colors hover:bg-accent/50"
onClick={() => openChangedFileInEditor(file.path)}
>
<span className="truncate">{file.path}</span>
<span className="shrink-0">
<span className="text-success">+{file.insertions}</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">-{file.deletions}</span>
</span>
</button>
))}
</div>
</ScrollArea>
<div className="flex justify-end font-mono">
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</div>
</div>
)}
</div>
</div>
{activeDialogAction === "commit" && (
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
)}
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
size="sm"
onClick={() => {
setActiveDialogAction(null);
setDialogCommitMessage("");
}}
>
Cancel
</Button>
<Button size="sm" onClick={runDialogAction}>
{activeDialogAction === "commit"
? "Commit"
: activeDialogAction === "push"
? "Push"
: "Create PR"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
</>
);
}
-21
View File
@@ -1,21 +0,0 @@
import type { SVGProps } from "react";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
export const GitHubIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 1024 1024" fill="none">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
transform="scale(64)"
fill="currentColor"
/>
</svg>
);
export const CursorIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 466.73 532.09" fill="currentColor">
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
</svg>
);
-575
View File
@@ -1,575 +0,0 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
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 inferProjectName(cwd: string): string {
const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const last = parts[parts.length - 1];
return last && last.length > 0 ? last : "project";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
colorClass: string;
dotClass: string;
pulse: boolean;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
pulse: boolean;
}
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurnCompletedAt) return false;
const completedAt = Date.parse(thread.latestTurnCompletedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Awaiting response",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
if (thread.runningTerminalIds.length === 0) {
return null;
}
return {
label: "Terminal process running",
colorClass: "text-teal-600 dark:text-teal-300/90",
pulse: true,
};
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
});
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(
gitRemoveWorktreeMutationOptions({ api, queryClient }),
);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(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,
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: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
},
[dispatch, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: string) => {
const latestThread = state.threads
.filter((thread) => thread.projectId === projectId)
.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);
})[0];
if (!latestThread) return;
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: latestThread.id,
});
},
[dispatch, state.threads],
);
const addProjectFromPath = useCallback(
async (rawCwd: string) => {
const cwd = rawCwd.trim();
if (!cwd || isAddingProject) return;
setIsAddingProject(true);
try {
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
}
} finally {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
}
},
[
api,
dispatch,
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
state.projects,
],
);
const handleAddProject = () => {
void addProjectFromPath(newCwd);
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
await addProjectFromPath(pickedPath);
} finally {
setIsPickingFolder(false);
}
};
const handleThreadContextMenu = useCallback(
async (threadId: string, position: { x: number; y: number }) => {
if (!api) return;
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
// Stop active session if running
if (thread.session?.sessionId) {
try {
await api.providers.stopSession({
sessionId: thread.session.sessionId,
});
} catch {
// Session may already be stopped
}
}
try {
await api.terminal.close({
threadId,
deleteHistory: true,
});
} catch {
// Terminal may already be closed
}
dispatch({ type: "DELETE_THREAD", threadId });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
});
} catch {
// Worktree deletion is best-effort and should not block thread deletion.
}
},
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [handleNewThread, keybindings, 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">
{/* Branding */}
<div
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</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 = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const terminalStatus = terminalStatusIndicator(thread);
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,
})
}
onContextMenu={(e) => {
e.preventDefault();
void handleThreadContextMenu(thread.id, {
x: e.clientX,
y: e.clientY,
});
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<div className="ml-2 flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<span className="text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</div>
</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);
}}
/>
{isElectron && 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 || isAddingProject}
>
{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}
disabled={isAddingProject}
>
{isAddingProject ? "Adding..." : "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>
);
}
@@ -1,894 +0,0 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import {
extractTerminalLinks,
isTerminalLinkActivation,
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type ThreadTerminalGroup,
} from "../types";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
}
function clampDrawerHeight(height: number): number {
const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
const maxHeight = maxDrawerHeight();
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
}
function writeSystemMessage(terminal: Terminal, message: string): void {
terminal.write(`\r\n[terminal] ${message}\r\n`);
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
const background =
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
if (isDark) {
return {
background,
foreground,
cursor: "rgb(180, 203, 255)",
selectionBackground: "rgba(180, 203, 255, 0.25)",
scrollbarSliderBackground: "rgba(255, 255, 255, 0.1)",
scrollbarSliderHoverBackground: "rgba(255, 255, 255, 0.18)",
scrollbarSliderActiveBackground: "rgba(255, 255, 255, 0.22)",
black: "rgb(24, 30, 38)",
red: "rgb(255, 122, 142)",
green: "rgb(134, 231, 149)",
yellow: "rgb(244, 205, 114)",
blue: "rgb(137, 190, 255)",
magenta: "rgb(208, 176, 255)",
cyan: "rgb(124, 232, 237)",
white: "rgb(210, 218, 230)",
brightBlack: "rgb(110, 120, 136)",
brightRed: "rgb(255, 168, 180)",
brightGreen: "rgb(176, 245, 186)",
brightYellow: "rgb(255, 224, 149)",
brightBlue: "rgb(174, 210, 255)",
brightMagenta: "rgb(229, 203, 255)",
brightCyan: "rgb(167, 244, 247)",
brightWhite: "rgb(244, 247, 252)",
};
}
return {
background,
foreground,
cursor: "rgb(38, 56, 78)",
selectionBackground: "rgba(37, 63, 99, 0.2)",
scrollbarSliderBackground: "rgba(0, 0, 0, 0.15)",
scrollbarSliderHoverBackground: "rgba(0, 0, 0, 0.25)",
scrollbarSliderActiveBackground: "rgba(0, 0, 0, 0.3)",
black: "rgb(44, 53, 66)",
red: "rgb(191, 70, 87)",
green: "rgb(60, 126, 86)",
yellow: "rgb(146, 112, 35)",
blue: "rgb(72, 102, 163)",
magenta: "rgb(132, 86, 149)",
cyan: "rgb(53, 127, 141)",
white: "rgb(210, 215, 223)",
brightBlack: "rgb(112, 123, 140)",
brightRed: "rgb(212, 95, 112)",
brightGreen: "rgb(85, 148, 111)",
brightYellow: "rgb(173, 133, 45)",
brightBlue: "rgb(91, 124, 194)",
brightMagenta: "rgb(153, 107, 172)",
brightCyan: "rgb(70, 149, 164)",
brightWhite: "rgb(236, 240, 246)",
};
}
interface TerminalViewportProps {
api: NativeApi;
threadId: string;
terminalId: string;
cwd: string;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
drawerHeight: number;
}
function TerminalViewport({
api,
threadId,
terminalId,
cwd,
focusRequestId,
autoFocus,
resizeEpoch,
drawerHeight,
}: TerminalViewportProps) {
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
useEffect(() => {
const mount = containerRef.current;
if (!mount) return;
let disposed = false;
const fitAddon = new FitAddon();
const terminal = new Terminal({
cursorBlink: true,
lineHeight: 1.2,
fontSize: 12,
scrollback: 5_000,
fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
theme: terminalThemeFromApp(),
});
terminal.loadAddon(fitAddon);
terminal.open(mount);
fitAddon.fit();
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const sendClearShortcut = async () => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
} catch (error) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Failed to clear terminal",
);
}
};
terminal.attachCustomKeyEventHandler((event) => {
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
void sendClearShortcut();
return false;
});
const terminalLinksDisposable = terminal.registerLinkProvider({
provideLinks: (bufferLineNumber, callback) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) {
callback(undefined);
return;
}
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
if (!line) {
callback(undefined);
return;
}
const lineText = line.translateToString(true);
const matches = extractTerminalLinks(lineText);
if (matches.length === 0) {
callback(undefined);
return;
}
callback(
matches.map((match) => ({
text: match.text,
range: {
start: { x: match.start + 1, y: bufferLineNumber },
end: { x: match.end, y: bufferLineNumber },
},
activate: (event: MouseEvent) => {
if (!isTerminalLinkActivation(event)) {
return;
}
const latestTerminal = terminalRef.current;
if (!latestTerminal) {
return;
}
if (match.kind === "url") {
void api.shell.openExternal(match.text).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open link",
);
});
return;
}
const target = resolvePathLinkTarget(match.text, cwd);
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
);
});
},
})),
);
},
});
const inputDisposable = terminal.onData((data) => {
void api.terminal
.write({ threadId, terminalId, data })
.catch((err) =>
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Terminal write failed",
),
);
});
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
activeTerminal.options.theme = terminalThemeFromApp();
activeTerminal.refresh(0, activeTerminal.rows - 1);
});
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class", "style"],
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const unsubscribe = api.terminal.onEvent((event) => {
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (event.type === "output") {
activeTerminal.write(event.data);
return;
}
if (event.type === "started" || event.type === "restarted") {
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
}
return;
}
if (event.type === "cleared") {
activeTerminal.clear();
activeTerminal.write("\u001bc");
return;
}
if (event.type === "error") {
writeSystemMessage(activeTerminal, event.message);
return;
}
if (event.type === "exited") {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
}
});
const fitTimer = window.setTimeout(() => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, 30);
void openTerminal();
return () => {
disposed = true;
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
terminalLinksDisposable.dispose();
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
const terminal = terminalRef.current;
if (!terminal) return;
const frame = window.requestAnimationFrame(() => {
terminal.focus();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [autoFocus, focusRequestId]);
useEffect(() => {
const terminal = terminalRef.current;
const fitAddon = fitAddonRef.current;
if (!terminal || !fitAddon) return;
const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
const frame = window.requestAnimationFrame(() => {
fitAddon.fit();
if (wasAtBottom) {
terminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: terminal.cols,
rows: terminal.rows,
})
.catch(() => undefined);
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
height: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
}
interface TerminalActionButtonProps {
label: string;
className: string;
onClick: () => void;
children: ReactNode;
}
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger openOnHover
render={
<button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
>
{children}
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{label}
</PopoverPopup>
</Popover>
);
}
export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
height,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
focusRequestId,
onSplitTerminal,
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
const normalizedTerminalIds = useMemo(() => {
const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
}, [terminalIds]);
const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
? activeTerminalId
: (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const resolvedTerminalGroups = useMemo(() => {
const validTerminalIdSet = new Set(normalizedTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
nextGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
for (const terminalId of normalizedTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
if (nextGroups.length > 0) {
return nextGroups;
}
return [
{
id: `group-${resolvedActiveTerminalId}`,
terminalIds: [resolvedActiveTerminalId],
},
];
}, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
const resolvedActiveGroupIndex = useMemo(() => {
const indexById = resolvedTerminalGroups.findIndex(
(terminalGroup) => terminalGroup.id === activeTerminalGroupId,
);
if (indexById >= 0) return indexById;
const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
);
return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
resolvedActiveTerminalId,
];
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const terminalLabelById = useMemo(
() =>
new Map(
normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
),
[normalizedTerminalIds],
);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback((nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
}, []);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
}, []);
const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
}, []);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
setResizeEpoch((value) => value + 1);
},
[syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
setResizeEpoch((value) => value + 1);
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
return (
<aside
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
</div>
</div>
)}
<div className="min-h-0 w-full flex-1">
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full gap-0 overflow-x-auto"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
}}
>
{visibleTerminalIds.map((terminalId) => (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
api={api}
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
</div>
))}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
api={api}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
)}
</div>
{hasTerminalSidebar && (
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<TerminalActionButton
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
label={
splitShortcutLabel
? `Split Terminal (${splitShortcutLabel})`
: "Split Terminal"
}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive =
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
return (
<div key={terminalGroup.id} className="pb-0.5">
{showGroupHeaders && (
<button
type="button"
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
isGroupActive
? "bg-accent/70 text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
>
{terminalGroup.terminalIds.length > 1
? `Split ${groupIndex + 1}`
: `Terminal ${groupIndex + 1}`}
</button>
)}
<div
className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
return (
<div
key={terminalId}
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
>
{showGroupHeaders && (
<span className="text-[10px] text-muted-foreground/80">└</span>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1 text-left"
onClick={() => onActiveTerminalChange(terminalId)}
>
<TerminalSquare className="size-3 shrink-0" />
<span className="truncate">
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
)}
</div>
</div>
</aside>
);
}
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more