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
402 changed files with 20959 additions and 68942 deletions

No files matched your search

+4 -14
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
@@ -17,12 +17,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
bun-version: 1.3.9
- name: Cache Bun and Turbo
uses: actions/cache@v4
@@ -46,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
@@ -10,4 +10,3 @@ packages/*/dist
.env.local
build/
.logs/
release/
+1 -3
View File
@@ -3,11 +3,9 @@
"ignorePatterns": [
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"*.tsbuildinfo"
],
"experimentalSortPackageJson": {}
}
+2 -11
View File
@@ -1,13 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
],
"ignorePatterns": ["dist", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
@@ -15,8 +8,6 @@
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"react-in-jsx-scope": "off"
}
}
+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
-42
View File
@@ -1,42 +0,0 @@
PR 1: Service contracts + error taxonomy
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
No behavior change yet, just interfaces and compile-time wiring points.
PR 2: CheckpointStore Effect adapter
Wrap current filesystemCheckpointStore behind CheckpointStoreLive (adapter).
Map all thrown/Promise errors to tagged errors.
Add service tests proving parity for isGitRepository, capture, restore, diff, prune.
PR 3: CodexService Effect adapter
Wrap current CodexAppServerManager behind CodexServiceLive (adapter).
Convert public API to Effect return types with typed errors.
Preserve existing EventEmitter internally for now, but expose Effect-friendly subscribe API.
PR 4: ProviderService Effect adapter
Wrap current ProviderManager behind ProviderServiceLive (adapter).
Provider methods become Effect methods with typed errors.
Route emitted provider events through an Effect PubSub surface.
PR 5: wsServer migration to Effect services
Stop instantiating provider/codex classes directly in wsServer.
Resolve ProviderService (and related services) from one runtime/layer graph.
Keep WS contract behavior identical.
PR 6: Native CheckpointStore implementation
Refactor checkpoint internals from Promise/throws to native Effect.
Replace ad-hoc locking with Effect concurrency primitive (keyed lock/semaphore/queue).
Keep adapter tests plus new failure-path tests.
PR 7: Codex transport/RPC core as native Effect
Split codex into scoped process layer + RPC request/response layer + session registry.
Replace timeout/pending maps with Deferred + Effect timeout/finalizer semantics.
Keep protocol behavior and ordering guarantees.
PR 8: Codex protocol decoding hardening
Replace ad-hoc unknown parsing with runtime schema decoding for inbound/outbound protocol shapes.
Map decode failures to typed tagged errors (with root cause).
Add regression tests for malformed/partial protocol messages.
PR 9: Native ProviderService orchestration
Rebuild provider logic in Effect using CodexService + CheckpointStore dependencies.
Move event fanout, checkpoint capture/revert orchestration, thread-log routing to Effect state/services.
Remove throw-based flow entirely from provider path.
PR 10: Cleanup + deprecation removal
Remove legacy class implementations/adapters once parity is proven.
Finalize layer composition and startup graph docs.
Add architecture notes for service boundaries and error model.
-58
View File
@@ -1,58 +0,0 @@
# Effect Migration Plan (From Current State)
Current status summary:
- Service contracts, typed errors, and most checkpoint/persistence services exist.
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
- Resolve `ProviderService` from runtime in `wsServer`.
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
- Forward provider events by subscribing to `ProviderService.subscribeToEvents`.
- Keep WS method/push payloads identical.
## PR 2: Runtime Composition + Startup Ownership
- Create/centralize `AppLive` composition for server startup.
- Ensure outer runtime provides Node/platform services once.
- Ensure migrations run at startup via scoped/layer startup path.
- Remove ad-hoc service initialization in request-time paths.
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
- Remove per-session lock/cwd map leaks.
- Keep strict invariant model:
- root checkpoint created at session initialization before agent modifications
- each completed turn captures filesystem checkpoint and persists metadata
- no after-the-fact metadata rebuild/sync
- Add tests for lifecycle cleanup and invariant-failure surfaces.
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
- Keep `ProviderService` as the public event surface.
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
- Add tests for ordering and subscriber isolation under load.
## PR 5: Codex Runtime Split (Scoped Effect Core)
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
- scoped process lifecycle
- RPC request/response + pending map via `Deferred`
- session registry/state
- Keep `CodexAdapter` contract stable while swapping internals.
- Preserve protocol behavior and timeout semantics.
## PR 6: Codex Protocol Decode Hardening
- Replace ad-hoc unknown parsing with runtime schema decode.
- Map decode failures to typed tagged errors with `cause` retained.
- Add regression tests for malformed/partial protocol frames.
## PR 7: Remove Legacy Provider Stack
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
- Update tests to assert only Effect service path is used.
## PR 8: Final Cleanup + Docs
- Update architecture docs with final layer graph and service boundaries.
- Document error model and recovery semantics.
- Trim dead compatibility code and stale plan references.
@@ -1,110 +0,0 @@
# ProviderService Integration Test Plan
Goal:
- Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive`
- `CheckpointServiceLive`
- `CheckpointStoreLive`
- `CheckpointRepositoryLive` (sqlite in-memory)
- `ProviderSessionDirectoryLive`
- Only fake the adapter event source (deterministic Codex-like stream).
- Avoid mocking checkpointing/persistence orchestration logic.
## Test Harness
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
- Internal state:
- session registry (session + cwd + threadId)
- thread snapshot store (`threadId`, `turns`)
- event subscribers
- Behavior:
- `startSession`: creates session with threadId.
- `sendTurn`: appends a deterministic turn snapshot and emits ordered events:
- `turn/started`
- `item/started` / `item/completed` (tool + approval variants depending on scenario)
- `item/agentMessage/delta` chunks
- `turn/completed`
- optional "mutator" callback per turn to change workspace files before completion.
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
Use real git-backed temporary workspaces in integration tests:
- initialize repo with baseline commit
- run provider turn in workspace
- assert checkpoint diffs against real git refs
## Core Integration Specs
1) `startSession` initializes checkpoint root exactly once
- Arrange:
- start provider session in git repo.
- Assert:
- `provider_checkpoints` contains root row (turn 0).
- checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root.
2) Turn without filesystem change
- Arrange:
- emit normal turn events, no file mutation.
- Assert:
- provider subscribers receive:
- `turn/started`
- `turn/completed`
- synthetic `checkpoint/captured`
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3) Turn with filesystem change
- Arrange:
- mutate `README.md` during turn.
- Assert:
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`.
4) Multi-turn sequencing and checkpoint monotonicity
- Arrange:
- turn 1: no file change
- turn 2: file change
- turn 3: file change
- Assert:
- turn counts are monotonic and contiguous in DB (0,1,2,3).
- latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas.
5) Revert to checkpoint
- Arrange:
- execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`.
- Assert:
- workspace content matches turn 1 state.
- adapter `rollbackThread` called with `numTurns=2`.
- DB rows for turns >1 are removed.
- later refs are deleted from git.
6) Capture failure surface
- Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert:
- `ProviderService` emits `checkpoint/captureError`.
- no partial metadata/ref divergence is left behind.
## WebSocket Coverage (Thin Integration)
Add one ws server integration spec:
- Subscribe to `providers.event`.
- Run a deterministic provider turn through ws methods.
- Assert push stream includes:
- `turn/started`, tool events, `turn/completed`, `checkpoint/captured`.
- Assert orchestration projection still updates assistant message and turn diff summary.
## Proposed PR Split
PR A:
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
PR B:
- Core ProviderService integration specs (cases 1-4).
PR C:
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
@@ -1,215 +0,0 @@
# Server-Authoritative Event-Sourcing Cleanup Plan
Goal:
- Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing
- strict command routing/validation
- pluggable provider adapters
- explicit separation between transport, domain orchestration, provider runtime, and persistence
## Target Service Graph (ASCII)
```text
+---------------------------+
| wsServer |
| transport |
+---------------------------+
| orchestration.dispatchCommand
v
+-------------------------------------------+
| OrchestrationCommandRouter |
+-------------------------------------------+
|
v
+-------------------------------------------+
| OrchestrationCommandHandlers |
+-------------------------------------------+
|
v
+-------------------------------------------+
| OrchestrationEventStore |
+-------------------------------------------+
|
v
+-------------------------------------------+
| OrchestrationProjectionService |
+-------------------------------------------+
| snapshot/replay
+---------------------------> wsServer
wsServer -- providers.* RPC --> +---------------------------+
| ProviderService |
+---------------------------+
| |
v v
+-------------------+ +-------------------------+
| ProviderSession | | ProviderAdapterRegistry |
| Registry (durable)| +-------------------------+
+-------------------+ |
^ v
| +-------------------------+
| | ProviderAdapter(s) |
| +-------------------------+
| |
| runtime events v
| +---------------------------+
+----------| ProviderRuntimeIngestion |
+---------------------------+
| | |
v v v
Router Session Checkpoint
Registry Service
+-------------------------------------------+
| CheckpointService |
+-------------------------------------------+
| | |
v v v
+--------------------+ +-------------+ +-------------------+
| CheckpointCatalog | | Checkpoint | | ProviderAdapter(s)|
| (durable) | | Store (git) | | (read/rollback) |
+--------------------+ +-------------+ +-------------------+
|
v
+------+
|SQLite|
+------+
OrchestrationEventStore ------> SQLite
OrchestrationProjectionService -> SQLite
ProviderSessionRegistry ------> SQLite
CheckpointCatalog ------> SQLite
```
## Commit Series
### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types:
- `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema`
- `OrchestrationCommandSchema = union(client, system)`
- Ensure client transport can only submit client commands.
- Keep system commands for server-internal workflows only.
- Expected files:
- `packages/contracts/src/orchestration.ts`
- `apps/server/src/wsServer.ts`
- orchestration/service tests
- Tests:
- reject system-only command via WS dispatch path
- preserve internal dispatch functionality for system commands
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
- Add dedicated router service to validate, authorize, and route commands.
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
- Expected files:
- `apps/server/src/orchestration/Services/CommandRouter.ts` (new)
- `apps/server/src/orchestration/Layers/CommandRouter.ts` (new)
- `apps/server/src/orchestration/Layer.ts`
- `apps/server/src/orchestration/reducer.ts` (only if needed for event payload changes)
- Tests:
- router validation and invariant failures
- handler happy-path tests per command type
### Commit 3: Harden event store for idempotency + optimistic append metadata
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
- Add optional aggregate version metadata for future optimistic concurrency.
- Expected files:
- `apps/server/src/persistence/Migrations/00x_*.ts` (new migration)
- `apps/server/src/persistence/Services/OrchestrationEvents.ts`
- `apps/server/src/persistence/Layers/OrchestrationEvents.ts`
- Tests:
- duplicate command ID append returns same event/sequence (or explicit idempotent behavior)
- concurrent append behavior stays ordered and deterministic
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
- Create `ProviderRuntimeIngestionService` that:
- subscribes to `ProviderService.streamEvents`
- translates runtime events into orchestration commands
- dispatches through router/engine
- Remove provider-to-orchestration state mutation logic from `wsServer`.
- Expected files:
- `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts` (new)
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (new)
- `apps/server/src/wsServer.ts`
- Tests:
- ingestion service mapping tests (turn started/completed, message delta/completed, runtime error)
- ws integration confirms same external push behavior
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
- Keep in-memory cache optional, but source of truth must be persistent.
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
- Expected files:
- `apps/server/src/provider/Services/ProviderSessionDirectory.ts` (or new SessionRegistry service)
- `apps/server/src/provider/Layers/ProviderSessionDirectory.ts`
- `apps/server/src/persistence/Migrations/00x_*.ts` (new table/indexes)
- provider persistence tests
- Tests:
- survives server restart with correct mapping
- stale session cleanup semantics
### Commit 6: Re-key checkpoint metadata from session to thread identity
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
- Keep `session_id` as nullable metadata only.
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
- Expected files:
- `apps/server/src/persistence/Migrations/00x_*.ts` (checkpoint schema migration)
- `apps/server/src/persistence/Services/Checkpoints.ts`
- `apps/server/src/persistence/Layers/Checkpoints.ts`
- `apps/server/src/checkpointing/Layers/CheckpointService.ts`
- Tests:
- resume/new session over same thread sees same checkpoint history
- revert/diff still work after session churn
### Commit 7: Add durable projection persistence for orchestration read models
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
- Keep event stream as source of truth; projection rebuild stays deterministic.
- `getSnapshot` reads from projection store (memory cache optional).
- Expected files:
- `apps/server/src/persistence/Migrations/00x_*.ts` (projection tables)
- `apps/server/src/orchestration/*` projection service/layer
- `apps/server/src/wsServer.ts` (snapshot/replay path wiring)
- Tests:
- cold boot snapshot load without replaying full history in process
- projection rebuild from events yields same result as previous reducer semantics
### Commit 8: Narrow `ProviderService` responsibilities
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
- Preserve adapter pluggability and provider-neutral contracts.
- Expected files:
- `apps/server/src/provider/Layers/ProviderService.ts`
- new orchestration/checkpoint runtime coordinator service(s)
- Tests:
- provider service routing stays intact
- checkpoint capture still triggered by turn completion through new coordinator
### Commit 9: Look over schemas (contracts and events)
- Scan for unused schemas.
- Use effect/Schema everywhere
- Analyze which we need
- RPC Input/Output (both for routeRequest and command handler)
- Event payloads
- Persistence entities
### Commit 10: Remove dead legacy path and finalize docs
- Remove unused legacy manager/store path from active architecture:
- `providerManager.ts`
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
- Look over effect services for unused methods, errors, etc
- Update architecture docs with final service boundaries and boot/runtime graph.
- Expected files:
- legacy files + references
- `AGENTS.md`/docs as needed
- `.plans` docs linkage
- Tests:
- full server integration suite passes on Effect-only path
- no regressions in WS protocol behavior
## Risk Controls
- Keep WS method names and payload contracts stable throughout.
- Gate each commit with targeted integration tests before moving forward.
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
-10
View File
@@ -1,10 +0,0 @@
Rewrite `createServer` and `index.ts` to be Effect native.
Maybe use `effect/unstable/Socket` for the web socket server
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
- Migrate remaining runtime code to Effect
- `gitManager` -> `src/git`
- `terminalManager` -> `src/terminal` (Manager + PTY)
- ...
-145
View File
@@ -1,145 +0,0 @@
# PR #89 Review Remediation Plan (Phased)
## How To Use These Files
- Working checklist with updateable status per item (single source of truth): `.plans/16c-pr89-remediation-checklist.md`
- This file (`16-pr89-review-remediation-phases.md`): phase strategy and grouping.
## Scope
- Source: GitHub review comments on PR #89 (`Add server-side orchestration engine with event sourcing`).
- Triage baseline used here:
- Total threads: 185
- Outdated: 94 (excluded)
- Active unresolved: 85
- Invalid/false-positive: 3 (excluded)
- Duplicate reposts: collapsed
- Unique actionable findings after filtering: 58
- Post-rewrite validity audit: 5 additional stale items marked invalid, leaving 53 actionable (`34 valid` + `19 partially-valid`)
## Phase 0: Canonical Triage Lock
- Create a single tracking checklist for the 53 currently actionable findings.
- Map every duplicate thread to its canonical item.
- Mark invalid/false-positive items with explicit rationale.
Exit criteria:
- Every open thread is mapped to one canonical fix item or marked invalid.
## Phase 1: Runtime Survival and Critical Event Wiring
Related bug groups solved together:
- Worker loop/fiber fatal error handling in orchestration reactors.
- WebSocket message error boundaries and unhandled rejection guards.
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
Primary files:
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts`
Exit criteria:
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
- WS message handling cannot produce unhandled promise rejections.
- Invalid provider-event-channel review findings are closed with architecture rationale.
## Phase 2: State Consistency and Ordering
Related bug groups solved together:
- Fire-and-forget revert completion causing consistency windows.
- Non-atomic append/projection paths and retry behavior.
- Race-sensitive thread/event association issues.
Primary files:
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
Exit criteria:
- Revert flow is deterministically reflected in read model updates.
- Append/project failure mode is explicit and safe under retry.
- No cross-thread misassociation under concurrent runtime events.
## Phase 3: Checkpointing Correctness Bundle
Related bug groups solved together:
- Checkpoint input normalization consistency.
- Snapshot/projector coverage mismatches.
- Checkpoint ref/workspace CWD utility duplication.
- Checkpoint diff/error handling behavior gaps.
Primary files:
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts`
Exit criteria:
- Checkpoint capture/restore/revert paths use one normalization policy.
- Required projectors are actually represented in snapshot reads.
- Shared checkpoint/ref/CWD helpers are centralized.
## Phase 4: Memory and Lifecycle Hygiene
Related bug groups solved together:
- Unbounded in-memory dedup sets/maps.
- Missing cleanup/lifecycle protections in long-lived effects/resources.
Primary files:
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/config.ts`
Exit criteria:
- Long-running server memory does not grow unbounded from dedup bookkeeping.
- Resource cleanup paths are registered for interruption/shutdown.
## Phase 5: Transport, Parsing, and Platform Edge Cases
Related bug groups solved together:
- UTF-8 chunk boundary decode correctness.
- Markdown/file-link parsing edge cases.
- Shell/OS-specific PATH parsing behavior.
- Git rename parsing and small keybinding edge cases.
Primary files:
- `apps/server/src/wsServer.ts`
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
- `apps/web/src/markdown-links.ts`
- `apps/server/src/os-jank.ts`
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/keybindings.ts`
Exit criteria:
- Edge-case parsers are robust across valid but non-trivial inputs.
- Platform-dependent command behavior has safe fallbacks.
## Phase 6: Build and Maintainability Cleanup
Related bug groups solved together:
- Build script/runtime assumption cleanup.
- Redundant error-union declarations and utility/type duplication.
- Non-functional cleanup comments/docs markers.
Primary files:
- `apps/server/package.json`
- `apps/server/src/checkpointing/Errors.ts`
- Shared utility locations introduced during earlier phases
- `AGENTS.md` (if cleanup is still pending)
Exit criteria:
- Build path is explicit and environment-safe.
- Redundant types/utilities are removed in favor of single sources of truth.
## Phase 7: Verification and Closeout
- Add backend tests for all behavioral fixes (integration-focused; external services may be layered/mocked, core business logic not mocked out).
- Run lint and backend tests for all touched packages.
- Resolve threads with fix references per canonical checklist item.
Exit criteria:
- Lint passes.
- Backend tests pass.
- All actionable review threads are resolved or explicitly justified.
-477
View File
@@ -1,477 +0,0 @@
# PR #89 Remediation Checklist (Consolidated)
_Last updated: 2026-02-26_
This is the working checklist for remediation execution.
Status values:
- `TODO`: Not started
- `IN_PROGRESS`: Currently being worked
- `BLOCKED`: Waiting on decision/dependency
- `DONE`: Implemented and verified
- `CLOSED_INVALID`: Stale/invalid review finding
Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
## Active Checklist
### Phase 1
- [x] `C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber.
- Status: `DONE`
- Verdict: `valid`
- Severity: `High`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:333`
- Threads: PRRT_kwDORLtfbc5wj4cH, PRRT_kwDORLtfbc5wnWwF, PRRT_kwDORLtfbc5wyTaP, PRRT_kwDORLtfbc5wzliw, PRRT_kwDORLtfbc5w0_g3, PRRT_kwDORLtfbc5w1HGT (+5 duplicate thread(s))
- Audit note: Ingestion worker loop can terminate on unhandled processEvent failure.
- [x] `C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake.
- Status: `DONE`
- Verdict: `valid`
- Severity: `High`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:75`
- Threads: PRRT_kwDORLtfbc5v-cf4
- Audit note: Upgrade reject writes then destroys socket without defensive error listener.
- [x] `C012` Forked revert dispatch risks read model inconsistency
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:542`
- Threads: PRRT_kwDORLtfbc5whszW, PRRT_kwDORLtfbc5wyTaS, PRRT_kwDORLtfbc5wzli0, PRRT_kwDORLtfbc5w0_g4, PRRT_kwDORLtfbc5w1HGX (+4 duplicate thread(s))
- Audit note: Revert completion dispatch remains forked; state consistency window remains.
- [ ] `C019` ProviderRuntimeIngestion processes events for wrong thread on race
- Status: `TODO`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:178`
- Threads: PRRT_kwDORLtfbc5wkPaL
- Audit note: SessionId-only routing can misassociate events under races/rebinds.
- [x] `C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop.
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:266`
- Threads: PRRT_kwDORLtfbc5w1GPr
- Audit note: Duplicate complete dispatch exists; downstream impact often idempotent.
- [x] `C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:545`
- Threads: PRRT_kwDORLtfbc5wj4cE
- Audit note: runPromise result still not caught; rejection can surface unhandled.
- [x] `C027` WS message handler can cause unhandled promise rejection
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/wsServer.ts:545`
- Threads: PRRT_kwDORLtfbc5wyTaW, PRRT_kwDORLtfbc5wzli3 (+1 duplicate thread(s))
- Audit note: Same unhandled rejection path remains in WS message handler.
- [x] `C042` Duplicated `resolveThreadWorkspaceCwd` across three files
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
- Threads: PRRT_kwDORLtfbc5wzli2
- Audit note: Duplication exists but one instance is variant logic, so impact is moderate.
- [x] `C043` Duplicated workspace CWD resolution logic across reactor modules
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
- Threads: PRRT_kwDORLtfbc5wnWwM, PRRT_kwDORLtfbc5w1C3-, PRRT_kwDORLtfbc5w1HGZ (+2 duplicate thread(s))
- Audit note: Workspace CWD resolution duplication still present across modules.
- [x] `C044` Checkpoint reactor swallows diff errors silently for `turn.completed`
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:274`
- Threads: PRRT_kwDORLtfbc5wkPaO
- Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy.
- [x] `C045` `truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:29`
- Threads: PRRT_kwDORLtfbc5wzp4R
- Audit note: truncateDetail still overshoots limit.
- [x] `C046` `latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Runtime resilience and failure handling`
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:133`
- Threads: PRRT_kwDORLtfbc5wxvIQ
- Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path.
- [x] `C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:83`
- Threads: PRRT_kwDORLtfbc5v-WPD
- Audit note: Still uses write+destroy rather than end() for rejection response.
- [ ] `C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:104`
- Threads: PRRT_kwDORLtfbc5whtrR
- Audit note: Array chunk UTF-8 decode remains vulnerable to split multibyte corruption.
- [x] `C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object.
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport _tag override risk exists but current callsites are constrained.
### Phase 2
- [x] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `High`
- Area: `Event ordering and state consistency`
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:96`
- Threads: PRRT_kwDORLtfbc5wzp4T
- Audit note: Append/project/receipt are non-atomic; retry can duplicate events.
- [x] `C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Event ordering and state consistency`
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:99`
- Threads: PRRT_kwDORLtfbc5whtrM
- Audit note: Persisted event can outpace in-memory projection on mid-flight failure.
- [x] `C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Event ordering and state consistency`
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:99`
- Threads: PRRT_kwDORLtfbc5whxJO
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Event ordering and state consistency`
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:490`
- Threads: PRRT_kwDORLtfbc5wxvH8
- Audit note: Pending turn-start map is in-memory only and not rebuilt on bootstrap.
### Phase 3
- [x] `C008` Inconsistent input normalization across CheckpointStore methods
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
- Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Checkpointing correctness`
- File: `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts:71`
- Threads: PRRT_kwDORLtfbc5wiLhQ
- Audit note: Snapshot sequence can under-report due to extra projectors, but replay impact is lower now.
- [x] `C033` Three error classes defined but never instantiated anywhere
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Errors.ts:51`
- Threads: PRRT_kwDORLtfbc5wlYgo
- Audit note: Original claim overstated; some errors used, others appear unused.
- [x] `C034` Redundant `CheckpointInvariantError` in `CheckpointServiceError` union type
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Errors.ts:79`
- Threads: PRRT_kwDORLtfbc5wj5fn
- Audit note: CheckpointInvariantError remains redundantly included in service union.
- [x] `C035` Redundant error type in CheckpointServiceError union definition
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Errors.ts:79`
- Threads: PRRT_kwDORLtfbc5wlYgs, PRRT_kwDORLtfbc5wxsO6, PRRT_kwDORLtfbc5w1C4B (+2 duplicate thread(s))
- Audit note: Same as C034.
### Phase 4
- [ ] `C018` Unbounded memory growth in turn start deduplication set
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Memory/resource growth`
- File: `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts:84`
- Threads: PRRT_kwDORLtfbc5whszQ, PRRT_kwDORLtfbc5wl2A8, PRRT_kwDORLtfbc5wyTaT, PRRT_kwDORLtfbc5wzliz, PRRT_kwDORLtfbc5w0_g-, PRRT_kwDORLtfbc5w1HGW (+5 duplicate thread(s))
- Audit note: handledTurnStartKeys still grows without pruning.
### Phase 5
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/git/Layers/GitCore.ts:41`
- Threads: PRRT_kwDORLtfbc5w1CxT
- Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts.
- [ ] `C010` `loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:418`
- Threads: PRRT_kwDORLtfbc5wxvIJ
- Audit note: ENOENT for missing keybindings config still not handled as empty/default.
- [ ] `C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning.
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/os-jank.ts:10`
- Threads: PRRT_kwDORLtfbc5wkRZM
- Audit note: fish PATH formatting risk still exists in os-jank path recovery.
- [ ] `C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output.
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/os-jank.ts:10`
- Threads: PRRT_kwDORLtfbc5wj4cM
- Audit note: -ilc shell invocation can pollute captured PATH output.
- [x] `C029` `parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:105`
- Threads: PRRT_kwDORLtfbc5wnVsU
- Audit note: file URL decoding still double-decodes in one path.
- [x] `C030` `EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:111`
- Threads: PRRT_kwDORLtfbc5wnVsK
- Audit note: Scheme regex still misclassifies script.ts:10 as external scheme.
- [ ] `C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/git/Layers/CodexTextGeneration.ts:136`
- Threads: PRRT_kwDORLtfbc5w1GPo
- Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters.
- [x] `C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:352`
- Threads: PRRT_kwDORLtfbc5wxvIB
- Audit note: Parser/encoder mismatch remains, but encoder path currently low-use.
- [x] `C040` `upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:488`
- Threads: PRRT_kwDORLtfbc5wxvIA
- Audit note: upsertKeybindingRule read-modify-write remains race-prone.
### Phase 6
- [ ] `C028` Branch sync dispatches both server and stale local update
- Status: `TODO`
- Verdict: `partially-valid`
- Severity: `Medium`
- Area: `Other`
- File: `apps/web/src/components/BranchToolbar.tsx:102`
- Threads: PRRT_kwDORLtfbc5v-XCu
- Audit note: Optimistic local+server dual update is intentional but can temporarily diverge.
- [x] `C037` `Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/config.ts:41`
- Threads: PRRT_kwDORLtfbc5wj4cO
- Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path.
- [ ] `C047` `SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts:75`
- Threads: PRRT_kwDORLtfbc5wiaR-
- Audit note: Decode and SQL errors still collapsed into one persistence error kind.
- [x] `C049` `JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/provider/Layers/ProviderService.ts:59`
- Threads: PRRT_kwDORLtfbc5wnVsI
- Audit note: JSON.stringify(cause) may return undefined despite string expectations.
- [ ] `C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:94`
- Threads: PRRT_kwDORLtfbc5wiLhY
- Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control.
- [x] `C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:119`
- Threads: PRRT_kwDORLtfbc5wxvH9
- Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated.
- [ ] `C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/terminal/Layers/BunPTY.ts:97`
- Threads: PRRT_kwDORLtfbc5w1CxE
- Audit note: Data callback may race before processHandle assignment.
- [ ] `C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists.
- Status: `TODO`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/web/src/components/ui/sidebar.tsx:114`
- Threads: PRRT_kwDORLtfbc5wxvIq
- Audit note: Bug pattern exists, but current callsites mostly avoid triggering it.
- [ ] `C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/web/src/routes/_chat.$threadId.tsx:105`
- Threads: PRRT_kwDORLtfbc5wyWz4
- Audit note: Resizable object recreation still retriggers effect/storage reads.
- [ ] `C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/web/src/routes/_chat.$threadId.tsx:122`
- Threads: PRRT_kwDORLtfbc5wnVsX
- Audit note: Number(null) -> 0 path still forces min width on initial load.
- [ ] `C060` `defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Low`
- Area: `Other`
- File: `packages/contracts/src/orchestration.ts:253`
- Threads: PRRT_kwDORLtfbc5whxJC
- Audit note: Schema still cannot express null clear for defaultModel patch.
## Closed Invalid Items
- [x] `C014` Engine error handler catches all errors including non-invariant ones
- Status: `CLOSED_INVALID`
- Severity: `Medium`
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:144`
- Threads: PRRT_kwDORLtfbc5wkPaJ
- Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design.
- [x] `C021` Shared mutable default metadata object causes stale eventId
- Status: `CLOSED_INVALID`
- Severity: `Medium`
- File: `apps/server/src/orchestration/decider.ts:27`
- Threads: PRRT_kwDORLtfbc5wkPaA
- Rationale: Stale-eventId claim no longer applies; eventId is regenerated per event.
- [x] `C025` Duplicated checkpoint ref computation across two files
- Status: `CLOSED_INVALID`
- Severity: `Medium`
- File: `apps/server/src/wsServer.ts:128`
- Threads: PRRT_kwDORLtfbc5wvwag
- Rationale: No longer duplicated; checkpoint ref helper now centralized.
- [x] `C031` Revert uses wrong turn count from positional inference
- Status: `CLOSED_INVALID`
- Severity: `Medium`
- File: `apps/web/src/session-logic.ts:127`
- Threads: PRRT_kwDORLtfbc5v9SCp
- Rationale: Revert now uses explicit checkpointTurnCount first; positional fallback is non-primary.
- [x] `C036` Duplicate `checkpointRefForThreadTurn` function in two production files
- Status: `CLOSED_INVALID`
- Severity: `Low`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:284`
- Threads: PRRT_kwDORLtfbc5wiqFX
- Rationale: No longer duplicated; single production source via Refs.ts.
- [x] `C055` Duplicate `checkpointRefForThreadTurn` function across files
- Status: `CLOSED_INVALID`
- Severity: `Low`
- File: `apps/server/src/wsServer.ts:128`
- Threads: PRRT_kwDORLtfbc5wkPaG
- Rationale: No longer duplicated; helper is centralized.
@@ -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
-201
View File
@@ -1,201 +0,0 @@
# Spec 1:1 Cutover Plan
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
Execution mode for this plan:
- Hard cutover only. Existing DB and migration history are disposable.
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
- We optimize for small, reviewable work units, not continuous app operability.
- Only the final gate requires everything to run cleanly.
## 1. Freeze SPEC contract as source of truth
Work units:
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
- Add app-level requirements per row: writer path, reader path, and owning module.
- Mark each row with status labels: `required`, `implemented`, `to-replace`, `delete`.
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
Deliverables:
- Complete matrix file with no unclassified rows.
- Single source checklist used by all later steps.
Breakage allowed:
- No code changes required yet.
Exit criteria:
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
## 2. Hard cutover migrations (replace current migration set)
Work units:
- Delete the current legacy migration files and rewrite migration loader ordering.
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
- Create `003_checkpoint_diff_blobs.ts` with uniqueness on `(thread_id, from_turn_count, to_turn_count)`.
- Create `004_provider_session_runtime.ts` with PK and runtime lookup indexes.
- Create `005_projections.ts` with all projection tables:
- `projection_projects`
- `projection_threads`
- `projection_thread_messages`
- `projection_thread_activities`
- `projection_thread_sessions`
- `projection_thread_turns`
- `projection_checkpoints`
- `projection_pending_approvals`
- `projection_state`
- Add all required indexes/constraints in `005_projections.ts`.
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
Deliverables:
- New 5-file migration chain.
- Updated migration loader references only new migrations.
Breakage allowed:
- Repositories/services can be temporarily broken due to removed old tables.
Exit criteria:
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
## 3. Align persistence row/request schemas to DB 1:1
Work units:
- Define row schemas for each canonical table (contracts or persistence layer module).
- Define request schemas for every insert/update/query operation touching canonical tables.
- Remove or deprecate row/request schemas tied to deleted legacy tables.
- Normalize enum and null semantics to match contracts exactly.
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
Deliverables:
- Canonical row/request schemas committed.
- Zero references to legacy row schemas in active code paths.
Breakage allowed:
- Runtime can still fail while query layers are being rewired.
Exit criteria:
- Every canonical table used in code has a typed row schema and typed request schema.
## 4. Rewrite event store for full persisted envelope
Work units:
- Refactor append path to write full envelope fields:
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
- Implement stream version assignment/checking per aggregate stream.
- Refactor read/replay path to decode payload and metadata from JSON and return `OrchestrationEvent` consistently.
- Remove assumptions from old minimal schema (`aggregate_id`, missing metadata/actor).
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
Deliverables:
- Event store append/replay fully aligned with canonical envelope.
Breakage allowed:
- Command dispatch flow can be partially broken until receipts/projectors are updated.
Exit criteria:
- Event store no longer depends on legacy event table shape.
## 5. Add command receipt idempotency
Work units:
- Introduce persistence access layer for `orchestration_command_receipts`.
- In command dispatch flow, check existing receipt by `commandId` before append.
- On first execution, persist accepted receipt with `resultSequence`.
- On domain rejection, persist rejected receipt with error payload.
- On duplicate command, return prior result from receipt without re-appending event.
- Ensure receipt write and event append ordering is deterministic.
Deliverables:
- Dispatch path with idempotency behavior wired through receipts.
Breakage allowed:
- Snapshot/read model may still be inconsistent until projectors are fully wired.
Exit criteria:
- Duplicate command IDs no longer create duplicate events.
## 6. Build DB-backed projection pipeline
Work units:
- Create projector runner that consumes events and applies table-specific projections.
- Implement projector handlers for each projection table.
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
- Define projector names used in `projection_state` and make them stable constants.
- Add replay bootstrap from event store to bring projections up to latest sequence on startup.
- Add safe resume logic from projector `last_applied_sequence`.
Deliverables:
- Persistent projector pipeline writing all `projection_*` tables.
Breakage allowed:
- Web/API layer may still read old in-memory model until step 7.
Exit criteria:
- Events drive projection rows in DB; projection state advances transactionally.
## 7. Move RPC reads to projections and diff blobs
Work units:
- Implement snapshot query service reading only projection tables.
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
- Implement `getTurnDiff` query backed by `checkpoint_diff_blobs` only.
- Remove or bypass in-memory snapshot construction for RPC responses.
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
Deliverables:
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
Breakage allowed:
- Provider runtime persistence may still be partially legacy until step 8.
Exit criteria:
- No orchestration read RPC depends on legacy tables or in-memory-only state.
## 8. Migrate provider runtime persistence to canonical table
Work units:
- Create repository/service for `provider_session_runtime`.
- Update adapter/session manager to persist runtime/resume cursor in new table.
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
- Remove writes to legacy provider session tables.
- Verify restart/resume path reads runtime state from canonical table only.
Deliverables:
- Provider runtime state entirely backed by `provider_session_runtime`.
Breakage allowed:
- Some legacy interfaces may still exist but should be disconnected.
Exit criteria:
- Runtime restore no longer reads/writes legacy provider session persistence.
## 9. Remove old cruft aggressively
Work units:
- Delete legacy repositories/services that map to removed tables.
- Remove dead migration imports and obsolete persistence service interfaces.
- Remove compatibility code paths that translate legacy row shapes.
- Remove unused contracts/types linked to deprecated persistence model.
- Update internal docs/comments to reference canonical projection/event model only.
Deliverables:
- Legacy persistence and translation layers removed from active codebase.
Breakage allowed:
- Temporary compile failures acceptable while deletion/refactor is in progress.
Exit criteria:
- No production code path references deleted legacy tables/services.
## 10. Final verification gate (first point where green is required)
Work units:
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
- Add receipt idempotency tests for accept/reject/duplicate paths.
- Add projector tests for transactional row updates + `projection_state` updates.
- Add snapshot tests verifying projection-sourced output and `snapshotSequence` semantics.
- Add turn diff tests verifying `checkpoint_diff_blobs` source of truth.
- Add provider runtime tests for persist + restart + resume behavior.
- Run project lint/typecheck/tests and fix failures.
Deliverables:
- Green checks with canonical schema + persistence model in place.
Breakage allowed:
- None at end of step.
Exit criteria:
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
-401
View File
@@ -1,401 +0,0 @@
# SPEC Contract Matrix (Sections 7.1-7.4)
Status legend:
- `required`: requirement acknowledged, no current implementation claim yet.
- `implemented`: requirement currently satisfied in code + schema.
- `to-replace`: partial/misaligned implementation exists and must be replaced.
- `delete`: current path actively conflicts with SPEC and should be removed.
## 7.1 Write-Side Persisted Tables
### W1
- Spec ref: `7.1.1 orchestration_events`
- Requirement: append-only event store with canonical envelope columns.
- SQL contract:
- `sequence INTEGER PRIMARY KEY` (global monotonic)
- `event_id TEXT UNIQUE NOT NULL`
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
- `stream_id TEXT NOT NULL`
- `stream_version INTEGER NOT NULL`
- `event_type TEXT NOT NULL`
- `occurred_at TEXT NOT NULL`
- `command_id TEXT NULL`
- `causation_event_id TEXT NULL`
- `correlation_id TEXT NULL`
- `actor_kind TEXT NOT NULL CHECK IN ('client','server','provider')`
- `payload_json TEXT NOT NULL`
- `metadata_json TEXT NOT NULL`
- Current writer path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
- Owner module: `apps/server/src/persistence` (event store + migrations)
- Status: `to-replace`
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
### W2
- Spec ref: `7.1.2 orchestration_command_receipts`
- Requirement: command idempotency + ack replay receipts table.
- SQL contract:
- `command_id TEXT PRIMARY KEY`
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
- `aggregate_id TEXT NOT NULL`
- `accepted_at TEXT NOT NULL`
- `result_sequence INTEGER NOT NULL`
- `status TEXT NOT NULL CHECK IN ('accepted','rejected')`
- `error TEXT NULL`
- Current writer path: none
- Current reader path: none
- Owner module: `apps/server/src/orchestration` dispatch boundary + `apps/server/src/persistence`
- Status: `to-replace`
- Notes: missing table and missing idempotency flow.
### W3
- Spec ref: `7.1.3 checkpoint_diff_blobs`
- Requirement: store large plaintext diffs separate from checkpoint summaries.
- SQL contract:
- `thread_id TEXT NOT NULL`
- `from_turn_count INTEGER NOT NULL`
- `to_turn_count INTEGER NOT NULL`
- `diff TEXT NOT NULL`
- `created_at TEXT NOT NULL`
- `UNIQUE(thread_id, from_turn_count, to_turn_count)`
- Current writer path: none
- Current reader path: none
- Owner module: `apps/server/src/persistence` + turn diff query service
- Status: `to-replace`
- Notes: no canonical diff blob table yet.
### W4
- Spec ref: `7.1.4 provider_session_runtime`
- Requirement: server-internal provider runtime/resume state.
- SQL contract:
- `provider_session_id TEXT PRIMARY KEY`
- `thread_id TEXT NOT NULL`
- `provider_name TEXT NOT NULL`
- `adapter_key TEXT NOT NULL`
- `provider_thread_id TEXT NULL`
- `status TEXT NOT NULL CHECK IN ('starting','running','stopped','error')`
- `last_seen_at TEXT NOT NULL`
- `resume_cursor_json TEXT NULL`
- `runtime_payload_json TEXT NULL`
- Current writer path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
- Current reader path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
- Owner module: provider runtime manager + persistence runtime repository
- Status: `to-replace`
- Notes: existing `provider_sessions` schema is incompatible and too small.
## 7.2 Canonical Persisted Event Schema
### E1
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
- Requirement: full typed persisted event envelope in shared contracts.
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
- Current writer path: contracts defined in `packages/contracts/src/orchestration.ts`
- Current reader path: used by persistence decode boundaries (partial)
- Owner module: `packages/contracts`
- Status: `implemented`
- Notes: contract schema exists; DB + store mapping still incomplete.
### E2
- Spec ref: `7.2 Rules/payload discriminated by eventType`
- Requirement: `payload` validation keyed by `eventType`.
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
- Current writer path: `packages/contracts/src/orchestration.ts`
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` decode path
- Owner module: contracts + event store
- Status: `to-replace`
- Notes: decode is present but DB does not persist full envelope columns.
### E3
- Spec ref: `7.2 Rules/provider ids scope`
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
- Current writer path: `apps/server/src/orchestration/decider.ts` (metadata mostly empty)
- Current reader path: projector/event consumers
- Owner module: decider + provider ingestion + event store
- Status: `to-replace`
- Notes: metadata plumbing is incomplete in persistence path.
### E4
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
- Requirement: stream version monotonic per aggregate stream; enforced on write.
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
- Current writer path: none
- Current reader path: none
- Owner module: event store append logic + DB constraints
- Status: `to-replace`
- Notes: no stream version assignment/checking today.
## 7.3 Required Projected Tables (Read Models)
### P1
- Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table.
- SQL contract:
- `project_id TEXT PRIMARY KEY`
- `title TEXT NOT NULL`
- `workspace_root TEXT NOT NULL`
- `default_model TEXT NULL`
- `created_at TEXT NOT NULL`
- `updated_at TEXT NOT NULL`
- `deleted_at TEXT NULL`
- Current writer path: none (in-memory projector only)
- Current reader path: none (snapshot not DB-projected)
- Owner module: projector pipeline + snapshot query
- Status: `to-replace`
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
### P2
- Spec ref: `7.3.2 projection_threads`
- Requirement: persisted thread projection table.
- SQL contract:
- `thread_id TEXT PRIMARY KEY`
- `project_id TEXT NOT NULL`
- `title TEXT NOT NULL`
- `model TEXT NOT NULL`
- `branch TEXT NULL`
- `worktree_path TEXT NULL`
- `latest_turn_id TEXT NULL`
- `created_at TEXT NOT NULL`
- `updated_at TEXT NOT NULL`
- `deleted_at TEXT NULL`
- Current writer path: none (in-memory projector only)
- Current reader path: none (snapshot not DB-projected)
- Owner module: projector pipeline + snapshot query
- Status: `to-replace`
- Notes: missing table and projector writes.
### P3
- Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table.
- SQL contract:
- `message_id TEXT PRIMARY KEY`
- `thread_id TEXT NOT NULL`
- `turn_id TEXT NULL`
- `role TEXT NOT NULL CHECK IN ('user','assistant','system')`
- `text TEXT NOT NULL`
- `is_streaming INTEGER/BOOLEAN NOT NULL`
- `created_at TEXT NOT NULL`
- `updated_at TEXT NOT NULL`
- Current writer path: none (in-memory projector only)
- Current reader path: none (snapshot not DB-projected)
- Owner module: projector pipeline + snapshot query
- Status: `to-replace`
- Notes: missing table and message projection writes.
### P4
- Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table.
- SQL contract:
- `activity_id TEXT PRIMARY KEY`
- `thread_id TEXT NOT NULL`
- `turn_id TEXT NULL`
- `tone TEXT NOT NULL CHECK IN ('info','tool','approval','error')`
- `kind TEXT NOT NULL`
- `summary TEXT NOT NULL`
- `payload_json TEXT NOT NULL`
- `created_at TEXT NOT NULL`
- Current writer path: none (in-memory projector only)
- Current reader path: none (snapshot not DB-projected)
- Owner module: projector pipeline + snapshot query
- Status: `to-replace`
- Notes: no canonical activity projection persistence.
### P5
- Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table.
- SQL contract:
- `thread_id TEXT PRIMARY KEY`
- `status TEXT NOT NULL CHECK IN ('idle','starting','running','ready','interrupted','stopped','error')`
- `provider_name TEXT NULL`
- `provider_session_id TEXT NULL`
- `provider_thread_id TEXT NULL`
- `active_turn_id TEXT NULL`
- `last_error TEXT NULL`
- `updated_at TEXT NOT NULL`
- Current writer path: none (in-memory projector only)
- Current reader path: none (snapshot not DB-projected)
- Owner module: projector pipeline + snapshot query
- Status: `to-replace`
- Notes: current provider session table is not this domain projection.
### P6
- Spec ref: `7.3.6 projection_thread_turns`
- Requirement: persisted thread turn projection table.
- SQL contract:
- `turn_id TEXT PRIMARY KEY`
- `thread_id TEXT NOT NULL`
- `turn_count INTEGER NOT NULL`
- `status TEXT NOT NULL CHECK IN ('running','completed','interrupted','error')`
- `user_message_id TEXT NULL`
- `assistant_message_id TEXT NULL`
- `started_at TEXT NOT NULL`
- `completed_at TEXT NULL`
- Current writer path: none
- Current reader path: none
- Owner module: projector pipeline + session/turn query helpers
- Status: `to-replace`
- Notes: missing table and projection logic.
### P7
- Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table.
- SQL contract:
- `thread_id TEXT NOT NULL`
- `turn_id TEXT NOT NULL`
- `checkpoint_turn_count INTEGER NOT NULL`
- `checkpoint_ref TEXT NOT NULL`
- `status TEXT NOT NULL CHECK IN ('ready','missing','error')`
- `files_json TEXT NOT NULL`
- `assistant_message_id TEXT NULL`
- `completed_at TEXT NOT NULL`
- `UNIQUE(thread_id, checkpoint_turn_count)`
- Current writer path: legacy `provider_checkpoints` writes in `apps/server/src/persistence/Layers/Checkpoints.ts`
- Current reader path: legacy checkpoint repository
- Owner module: projector pipeline + checkpoint query layer
- Status: `to-replace`
- Notes: current table semantics do not match canonical checkpoint projection schema.
### P8
- Spec ref: `7.3.8 projection_pending_approvals`
- Requirement: persisted pending-approval projection table.
- SQL contract:
- `request_id TEXT PRIMARY KEY`
- `thread_id TEXT NOT NULL`
- `turn_id TEXT NULL`
- `status TEXT NOT NULL CHECK IN ('pending','resolved')`
- `decision TEXT NULL CHECK IN ('accept','acceptForSession','decline','cancel')`
- `created_at TEXT NOT NULL`
- `resolved_at TEXT NULL`
- Current writer path: none
- Current reader path: none
- Owner module: projector pipeline + approval query layer
- Status: `to-replace`
- Notes: missing table and projection logic.
### P9
- Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table.
- SQL contract:
- `projector TEXT PRIMARY KEY`
- `last_applied_sequence INTEGER NOT NULL`
- `updated_at TEXT NOT NULL`
- Current writer path: none
- Current reader path: none
- Owner module: projector runner/checkpointing
- Status: `to-replace`
- Notes: missing table and projector bookkeeping.
### P10
- Spec ref: `7.3 Projection consistency rules`
- Requirement: projector row updates and `projection_state` update must be atomic per event.
- SQL contract: per-projector transaction boundary covering both projection write and state update.
- Current writer path: none (in-memory projector has no SQL transaction)
- Current reader path: none
- Owner module: projector runner
- Status: `to-replace`
- Notes: requires transactional projection executor.
### P11
- Spec ref: `7.3 Optional debug field`
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
- SQL contract: optional; not required in baseline schema.
- Current writer path: none
- Current reader path: none
- Owner module: projector runner
- Status: `required`
- Notes: interpretation: exclude from first cutover unless debugging requires it.
## 7.4 Snapshot and RPC Requirements
### R1
- Spec ref: `7.4.1`
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
- Current writer path: in-memory model built in `apps/server/src/orchestration/projector.ts`
- Current reader path: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts#getReadModel`
- Owner module: snapshot query service + ws RPC handler
- Status: `delete`
- Notes: current in-memory read model path must be removed for SPEC compliance.
### R2
- Spec ref: `7.4.2`
- Requirement: snapshot `projects[]` source is `projection_projects`.
- SQL contract: `projects` collection assembled from `projection_projects` rows.
- Current writer path: none
- Current reader path: in-memory thread/project arrays
- Owner module: snapshot query service
- Status: `to-replace`
- Notes: no DB project projection reader exists yet.
### R3
- Spec ref: `7.4.3`
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
- Current writer path: legacy checkpoint repo data model
- Current reader path: in-memory checkpoints from orchestration events
- Owner module: snapshot query service + checkpoint projector
- Status: `to-replace`
- Notes: canonical projection table and reader not implemented.
### R4
- Spec ref: `7.4.4`
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
- Current writer path: none for diff blobs
- Current reader path: `orchestration.getTurnDiff` schema exists, data backing incomplete
- Owner module: ws RPC handler + diff query service
- Status: `to-replace`
- Notes: current checkpoint repository is not canonical source.
### R5
- Spec ref: `7.4.5`
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
- SQL contract: session lookup by `thread_id` from projection table.
- Current writer path: mixed provider/session handling paths
- Current reader path: legacy provider session persistence lookups
- Owner module: provider dispatch/session resolution
- Status: `to-replace`
- Notes: remove provider-session-as-routing-key behavior.
### R6
- Spec ref: `7.4.6`
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
- Current writer path: none
- Current reader path: currently from in-memory event projection sequence
- Owner module: snapshot query service
- Status: `to-replace`
- Notes: must move from in-memory sequence to DB projection-state semantics.
### R7
- Spec ref: `7.4.7`
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
- Current writer path: event stream via `OrchestrationEventStore.readFromSequence`
- Current reader path: ws replay flow in `apps/server/src/wsServer.ts`
- Owner module: ws RPC + event stream handoff layer
- Status: `to-replace`
- Notes: interpretation requires explicit consistency boundary (transaction, sequence fence, or equivalent).
## Ambiguous/Interpretation Decisions (tracked upfront)
### A1
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
## Checklist Completeness Statement
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
- Unclassified rows: `0`.
+1 -2
View File
@@ -4,6 +4,5 @@
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"oxc.unusedDisableDirectives": "warn"
}
+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 orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
- Session startup/resume and turn lifecycle are brokered in `packages/runtime-core/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `packages/runtime-core/src/providerManager.ts`.
- Renderer consumes provider event streams via `nativeApi.providers.onEvent`.
Docs:
-101
View File
@@ -1,101 +0,0 @@
# Keybindings
T3 Code reads keybindings from:
- `~/.t3/keybindings.json`
The file must be a JSON array of rules:
```json
[
{ "key": "mod+g", "command": "terminal.toggle" },
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
```json
[
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
### Rule Shape
Each entry supports:
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): action ID
- `when` (optional): boolean expression controlling when the shortcut is active
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
### Available Commands
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
### Key Syntax
Supported modifiers:
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
- `cmd` / `meta`
- `ctrl` / `control`
- `shift`
- `alt` / `option`
Examples:
- `mod+j`
- `mod+shift+d`
- `ctrl+l`
- `cmd+k`
### `when` Conditions
Currently available context keys:
- `terminalFocus`
- `terminalOpen`
Supported operators:
- `!` (not)
- `&&` (and)
- `||` (or)
- parentheses: `(` `)`
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "terminalFocus || terminalOpen"`
Unknown condition keys evaluate to `false`.
### Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- That means precedence is across commands, not only within the same command.
+130 -98
View File
@@ -1,124 +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
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# 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.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `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.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
### Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
### 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 orchestration read-model updates
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`
- `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`
-65
View File
@@ -1,65 +0,0 @@
# Remote Access Setup
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
## CLI ↔ Env option map
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ---------------------------------- |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
> TIP: Use the `--help` flag to see all available options and their descriptions.
## Security First
- Always set `--auth-token` before exposing the server outside localhost.
- Treat the token like a password.
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
## 1) Build + run server for remote access
Remote access should use the built web app (not local Vite redirect mode).
```bash
bun run build
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
```
Then open on your phone:
`http://<your-machine-ip>:3773`
Example:
`http://192.168.1.42:3773`
Notes:
- `--host 0.0.0.0` listens on all IPv4 interfaces.
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
- Ensure your OS firewall allows inbound TCP on the selected port.
## 2) Tailnet / Tailscale access
If you use Tailscale, you can bind directly to your Tailnet address.
```bash
TAILNET_IP="$(tailscale ip -4)"
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
```
Open from any device in your tailnet:
`http://<tailnet-ip>:3773`
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
-582
View File
@@ -1,582 +0,0 @@
# Orchestration Interface Spec (Required State)
Status: Required target architecture (not a description of current behavior).
## 1. Identifier Schema (Branded)
All identifiers are branded and never plain `string` in schema definitions.
```ts
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
const EventId = Schema.String.pipe(Schema.brand("EventId"));
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
```
Rules:
- `ThreadId` is app/orchestration thread identity.
- `ProviderThreadId` is provider runtime thread identity.
- They are never assigned to each other.
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
## 2. Client Commands (Domain Commands)
All commands are sent through one RPC: `orchestration.dispatchCommand`.
Output for every command: `DispatchResultSchema = { sequence: number }`.
### 2.1 Client-Dispatchable Commands
1. `project.create`
- Input:
- `commandId: CommandId`
- `projectId: ProjectId`
- `title: string`
- `workspaceRoot: string`
- `defaultModel?: string`
- `createdAt: IsoDateTime`
- Output: `DispatchResult`
2. `project.meta.update`
- Input:
- `commandId: CommandId`
- `projectId: ProjectId`
- optional `{ title, workspaceRoot, defaultModel, scripts }`
- Output: `DispatchResult`
3. `project.delete`
- Input: `commandId`, `projectId`
- Output: `DispatchResult`
4. `thread.create`
- Input:
- `commandId: CommandId`
- `threadId: ThreadId`
- `projectId: ProjectId`
- `title: string`
- `model: string`
- `branch: string | null`
- `worktreePath: string | null`
- `createdAt: IsoDateTime`
- Output: `DispatchResult`
5. `thread.delete`
- Input: `commandId`, `threadId`
- Output: `DispatchResult`
6. `thread.meta.update`
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
- Output: `DispatchResult`
7. `thread.turn.start`
- Input:
- `commandId`
- `threadId`
- `message`:
- `messageId: MessageId`
- `role: "user"`
- `text: string`
- `attachments: ChatAttachment[]` (schema-shared)
- `model?: string`
- `effort?: string`
- `createdAt`
- Output: `DispatchResult`
8. `thread.turn.interrupt`
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
- Output: `DispatchResult`
9. `thread.approval.respond`
- Input:
- `commandId`
- `threadId`
- `requestId: ApprovalRequestId`
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
- `createdAt`
- Output: `DispatchResult`
10. `thread.checkpoint.revert`
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
- Output: `DispatchResult`
11. `thread.session.stop`
- Input: `commandId`, `threadId`, `createdAt`
- Output: `DispatchResult`
### 2.2 Internal-Only Commands (Not Client Dispatchable)
1. `thread.session.set`
- Server-owned projection update for session lifecycle.
2. `thread.message.assistant.delta`
- Server-owned incremental assistant content append.
3. `thread.message.assistant.complete`
- Server-owned assistant message completion marker.
4. `thread.turn.diff.complete`
- Server-owned checkpoint diff summary write.
5. `thread.activity.append`
- Server-owned activity feed append.
## 3. Client RPC (Required)
These are the required client-facing RPC methods.
1. `orchestration.getSnapshot`
- Input: `{}`
- Output: `OrchestrationReadModel`
2. `orchestration.dispatchCommand`
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
- Output: `DispatchResult`
3. `orchestration.getTurnDiff`
- Input:
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- Output:
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- `diff: string`
4. `orchestration.replayEvents` (optional operational/debug API)
- Input: `{ fromSequenceExclusive: number }`
- Output: `OrchestrationEvent[]`
### 3.1 RPC To Remove
Remove from client boundary:
- `providers.startSession`
- `providers.sendTurn`
- `providers.interruptTurn`
- `providers.respondToRequest`
- `providers.stopSession`
- `providers.listCheckpoints`
- `providers.getCheckpointDiff`
- `providers.revertToCheckpoint`
Rationale:
- Session/turn/checkpoint control belongs to orchestrator command path.
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
## 4. Server Orchestrator Command <-> Event Schemas
Each command deterministically yields one or more domain events that are persisted to the event store.
1. `project.create` -> `project.created`
2. `project.meta.update` -> `project.meta-updated`
3. `project.delete` -> `project.deleted`
4. `thread.create` -> `thread.created`
5. `thread.delete` -> `thread.deleted`
6. `thread.meta.update` -> `thread.meta-updated`
7. `thread.turn.start` ->
- `thread.message-sent` (user message append)
- `thread.turn-start-requested`
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
9. `thread.approval.respond` -> `thread.approval-response-requested`
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
Internal command/event path:
- `thread.session.set` -> `thread.session-set`
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
- `thread.activity.append` -> `thread.activity-appended`
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
Required mapping pipeline:
`Raw Provider Event (adapter-specific)`
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
-> `Internal Orchestration Command`
-> `Orchestration Domain Event`
### 5.1 Mapping Table for Codex Adapter
1. Raw `thread/started`
- Generic: `thread.started`
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
- Domain event: `thread.session-set`
2. Raw `turn/started`
- Generic: `turn.started`
- Internal command: `thread.session.set` (status `running`, active turn)
- Domain event: `thread.session-set`
3. Raw `item/agentMessage/delta`
- Generic: `message.delta`
- Internal command: `thread.message.assistant.delta`
- Domain event: `thread.message-sent` (assistant, streaming)
4. Raw `item/completed` (agent message)
- Generic: `message.completed`
- Internal command: `thread.message.assistant.complete`
- Domain event: `thread.message-sent` (assistant, completed)
5. Raw `turn/completed`
- Generic: `turn.completed`
- Internal commands:
- `thread.session.set` (ready/error)
- `thread.activity.append` (optional summary)
- Domain events: `thread.session-set`, `thread.activity-appended`
6. Raw approval request
- Generic: `approval.requested`
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
- Domain event: `thread.activity-appended`
7. Raw approval decision ack
- Generic: `approval.resolved`
- Internal command: `thread.activity.append`
- Domain event: `thread.activity-appended`
8. Raw tool start/complete
- Generic: `tool.started` / `tool.completed`
- Internal command: `thread.activity.append`
- Domain event: `thread.activity-appended`
9. Checkpoint capture (server-produced)
- Generic: `checkpoint.captured`
- Internal command: `thread.turn.diff.complete`
- Domain event: `thread.turn-diff-completed`
10. Raw/runtime error
- Generic: `runtime.error`
- Internal commands:
- `thread.session.set` (status `error`)
- `thread.activity.append` (`tone=error`)
- Domain events: `thread.session-set`, `thread.activity-appended`
## 6. Schema Section (Boundary + Reuse)
### 6.1 Shared Schemas (contracts package)
Expose to both web and server:
- `OrchestrationReadModelSchema`
- `ClientOrchestrationCommandSchema`
- `OrchestrationEventSchema`
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
- Shared message/activity/checkpoint summary schemas used in snapshot
### 6.2 Server-Internal Schemas
Not exposed to web:
- `InternalOrchestrationCommandSchema`
- Adapter raw-event schemas and provider-specific payload schemas
- Provider session directory records and persistence-only row schemas
- Git service cache/query schemas (non-orchestration read model)
### 6.3 Reuse Requirements
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
## 7. Persistence Model (Required)
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
### 7.1 Write-Side Persisted Tables
1. `orchestration_events` (append-only event store)
- `sequence: number` (global monotonic sequence, primary key)
- `eventId: EventId` (unique)
- `aggregateKind: "project" | "thread"`
- `streamId: ProjectId | ThreadId` (aggregate stream id)
- `streamVersion: number` (per-aggregate monotonic version)
- `eventType: OrchestrationEventType`
- `occurredAt: IsoDateTime`
- `commandId: CommandId | null`
- `causationEventId: EventId | null`
- `correlationId: CommandId | null`
- `actorKind: "client" | "server" | "provider"`
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
- `metadata: OrchestrationEventMetadata`
2. `orchestration_command_receipts` (idempotency + ack replay)
- `commandId: CommandId` (primary key)
- `aggregateKind: "project" | "thread"`
- `aggregateId: ProjectId | ThreadId`
- `acceptedAt: IsoDateTime`
- `resultSequence: number`
- `status: "accepted" | "rejected"`
- `error: string | null`
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- `diff: string`
- `createdAt: IsoDateTime`
- unique key: `(threadId, fromTurnCount, toTurnCount)`
4. `provider_session_runtime` (server-internal adapter resume state)
- `providerSessionId: ProviderSessionId` (primary key)
- `threadId: ThreadId`
- `providerName: string`
- `adapterKey: string`
- `providerThreadId: ProviderThreadId | null`
- `status: "starting" | "running" | "stopped" | "error"`
- `lastSeenAt: IsoDateTime`
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
### 7.2 Canonical Persisted Event Schema
`OrchestrationPersistedEventSchema` (full envelope):
```ts
type OrchestrationPersistedEvent = {
sequence: number;
eventId: EventId;
aggregateKind: "project" | "thread";
streamId: ProjectId | ThreadId;
streamVersion: number;
eventType: OrchestrationEventType;
occurredAt: IsoDateTime;
commandId: CommandId | null;
causationEventId: EventId | null;
correlationId: CommandId | null;
actorKind: "client" | "server" | "provider";
payload: OrchestrationEventPayload;
metadata: {
providerSessionId?: ProviderSessionId;
providerThreadId?: ProviderThreadId;
providerTurnId?: ProviderTurnId;
providerItemId?: ProviderItemId;
adapterKey?: string;
requestId?: ApprovalRequestId;
ingestedAt?: IsoDateTime;
};
};
```
Rules:
- `payload` must be schema-discriminated by `eventType`.
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
- `streamVersion` is concurrency guard for aggregate writes.
### 7.3 Required Projected Tables (Read Models)
1. `projection_projects`
- `projectId: ProjectId` (primary key)
- `title: string`
- `workspaceRoot: string`
- `defaultModel: string | null`
- `scripts: ProjectScript[]`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
- `deletedAt: IsoDateTime | null`
2. `projection_threads`
- `threadId: ThreadId` (primary key)
- `projectId: ProjectId`
- `title: string`
- `model: string`
- `branch: string | null`
- `worktreePath: string | null`
- `latestTurnId: TurnId | null`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
- `deletedAt: IsoDateTime | null`
3. `projection_thread_messages`
- `messageId: MessageId` (primary key)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `role: "user" | "assistant" | "system"`
- `text: string`
- `isStreaming: boolean`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
4. `projection_thread_activities`
- `activityId: EventId` (primary key; derived from source event)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `tone: "info" | "tool" | "approval" | "error"`
- `kind: string`
- `summary: string`
- `payload: JsonValue`
- `createdAt: IsoDateTime`
5. `projection_thread_sessions`
- `threadId: ThreadId` (primary key)
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
- `providerName: string | null`
- `providerSessionId: ProviderSessionId | null`
- `providerThreadId: ProviderThreadId | null`
- `activeTurnId: TurnId | null`
- `lastError: string | null`
- `updatedAt: IsoDateTime`
6. `projection_thread_turns`
- `turnId: TurnId` (primary key)
- `threadId: ThreadId`
- `turnCount: number`
- `status: "running" | "completed" | "interrupted" | "error"`
- `userMessageId: MessageId | null`
- `assistantMessageId: MessageId | null`
- `startedAt: IsoDateTime`
- `completedAt: IsoDateTime | null`
7. `projection_checkpoints`
- `threadId: ThreadId`
- `turnId: TurnId`
- `checkpointTurnCount: number`
- `checkpointRef: CheckpointRef`
- `status: "ready" | "missing" | "error"`
- `files: JsonArray` (typed as file diff summary schema)
- `assistantMessageId: MessageId | null`
- `completedAt: IsoDateTime`
- unique key: `(threadId, checkpointTurnCount)`
8. `projection_pending_approvals`
- `requestId: ApprovalRequestId` (primary key)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `status: "pending" | "resolved"`
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
- `createdAt: IsoDateTime`
- `resolvedAt: IsoDateTime | null`
9. `projection_state`
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
- `lastAppliedSequence: number`
- `updatedAt: IsoDateTime`
Projection consistency rules:
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
### 7.4 Snapshot and RPC Requirements
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
2. Snapshot must include `projects[]` from `projection_projects`.
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
- `turnId: TurnId`
- `completedAt: IsoDateTime`
- `status`
- `files[]` (`path`, `kind`, `additions`, `deletions`)
- `checkpointRef: CheckpointRef`
- `assistantMessageId?: MessageId`
- `checkpointTurnCount: number`
4. Client does not require `listCheckpoints` RPC:
- checkpoint list comes from snapshot projections
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
5. Provider session identity is not a client routing key:
- client acts on `ThreadId`
- server resolves provider session internally via `projection_thread_sessions`
6. `snapshotSequence` is derived from `projection_state`:
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
7. Event subscription handoff contract:
- client performs `getSnapshot` and reads `snapshotSequence`
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
### 7.5 External Derived State (Non-Orchestration)
1. Current git/worktree state is not projected from orchestration events.
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
### 7.6 Existing Repository Placement
1. `ProjectsRepository`
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
- Must not bypass command->event append path for mutations.
2. `CheckpointsRepository`
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
- Must not be an independent source of truth outside orchestration events.
3. `ProviderSessionsRepository`
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
- Not part of client RPC/domain aggregate boundary.
+6 -19
View File
@@ -1,25 +1,12 @@
# TODO
## TODO
## Small things
- [ ] Plan mode
- [ ] Submitting new messages should scroll to bottom
- [ ] 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)
- [x] 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)
-2
View File
@@ -1,2 +0,0 @@
dist-electron/
.electron-runtime/
-29
View File
@@ -1,29 +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": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "40.6.0"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@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"
},
"productName": "T3 Code (Alpha)"
}
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 313 KiB

-70
View File
@@ -1,70 +0,0 @@
import { spawnSync } from "node:child_process";
import electronmon from "electronmon";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
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 childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
let shuttingDown = false;
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
}
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
process.exit(exitCode);
}
process.once("SIGINT", () => {
void shutdown(130);
});
process.once("SIGTERM", () => {
void shutdown(143);
});
process.once("SIGHUP", () => {
void shutdown(129);
});
-144
View File
@@ -1,144 +0,0 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import { spawnSync } from "node:child_process";
import {
copyFileSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
if (insertResult.status === 0) {
return;
}
const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
};
const currentMetadata = readJson(metadataPath);
if (
existsSync(targetBinaryPath) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
return targetBinaryPath;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
}
export function resolveElectronPath() {
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (process.platform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
-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);
});
-20
View File
@@ -1,20 +0,0 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 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.
}
}
-550
View File
@@ -1,550 +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, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } 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 MENU_ACTION_CHANNEL = "desktop:menu-action";
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
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;
let desktopProtocolRegistered = false;
protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
function resolveAppRoot(): string {
if (!app.isPackaged) {
return ROOT_DIR;
}
return app.getAppPath();
}
function resolveBackendEntry(): string {
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return os.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
path.join(appRoot, "apps/server/dist/client"),
path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (fs.existsSync(path.join(candidate, "index.html"))) {
return candidate;
}
}
return null;
}
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
if (normalizedPath.includes("..")) {
return path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
const resolvedPath = path.join(staticRoot, requestedPath);
if (path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = path.join(resolvedPath, "index.html");
if (fs.existsSync(nestedIndex)) {
return nestedIndex;
}
return path.join(staticRoot, "index.html");
}
function isStaticAssetRequest(requestUrl: string): boolean {
try {
const url = new URL(requestUrl);
return path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
function registerDesktopProtocol(): void {
if (isDevelopment || desktopProtocolRegistered) return;
const staticRoot = resolveDesktopStaticDir();
if (!staticRoot) {
throw new Error(
"Desktop static bundle missing. Build apps/server (with bundled client) first.",
);
}
const staticRootResolved = path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
const fallbackIndex = path.join(staticRootResolved, "index.html");
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
try {
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url);
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
if (isAssetRequest) {
callback({ error: -6 });
return;
}
callback({ path: fallbackIndex });
return;
}
callback({ path: resolvedCandidate });
} catch {
callback({ path: fallbackIndex });
}
});
desktopProtocolRegistered = true;
}
function dispatchMenuAction(action: string): void {
const existingWindow =
BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const targetWindow = existingWindow ?? createWindow();
if (!existingWindow) {
mainWindow = targetWindow;
}
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (!targetWindow.isVisible()) {
targetWindow.show();
}
targetWindow.focus();
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}
function configureApplicationMenu(): void {
const template: MenuItemConstructorOptions[] = [];
if (process.platform === "darwin") {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
template.push(
{
label: "File",
submenu: [
...(process.platform === "darwin"
? []
: [
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" as const },
]),
{ role: process.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
);
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
function resolveResourcePath(fileName: string): string | null {
const candidates = [
path.join(__dirname, "../resources", fileName),
path.join(process.resourcesPath, "resources", fileName),
path.join(process.resourcesPath, fileName),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
app.setAboutPanelOptions({
applicationName: APP_DISPLAY_NAME,
});
if (process.platform === "win32") {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
app.dock.setIcon(iconPath);
}
}
}
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;
const backendEntry = resolveBackendEntry();
if (!fs.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
return;
}
const child = spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
// 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.exitCode === null && child.signalCode === null) {
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
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 getIconOption(): { icon: string } | Record<string, never> {
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = process.platform === "win32" ? "ico" : "png";
const iconPath = resolveIconPath(ext);
return iconPath ? { icon: iconPath } : {};
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
autoHideMenuBar: true,
...getIconOption(),
title: APP_DISPLAY_NAME,
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.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
});
window.webContents.on("did-finish-load", () => {
window.setTitle(APP_DISPLAY_NAME);
});
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 {
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
}
window.on("closed", () => {
if (mainWindow === window) {
mainWindow = null;
}
});
return window;
}
configureAppIdentity();
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(() => {
configureAppIdentity();
configureApplicationMenu();
registerDesktopProtocol();
void bootstrap();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
if (process.platform !== "win32") {
process.on("SIGINT", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
process.on("SIGTERM", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
}
-28
View File
@@ -1,28 +0,0 @@
import { contextBridge, ipcRenderer } from "electron";
import type { DesktopBridge } from "@t3tools/contracts";
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 MENU_ACTION_CHANNEL = "desktop:menu-action";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
listener(action);
};
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
};
},
} satisfies DesktopBridge);
-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,36 +11,24 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"@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": {
"@effect/language-service": "catalog:",
"@tailwindcss/vite": "^4.0.0",
"@tanstack/router-plugin": "^1.161.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>
);
}
@@ -0,0 +1,28 @@
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
interface ChatMarkdownProps {
text: string;
}
const markdownComponents: Components = {
a({ node: _node, ...props }) {
return <a {...props} target="_blank" rel="noreferrer" />;
},
};
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
components={markdownComponents}
>
{text}
</ReactMarkdown>
</div>
);
}
+986
View File
@@ -0,0 +1,986 @@
import {
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type ProviderApprovalDecision,
type ProviderEvent,
} from "@acme/contracts";
import {
type FormEvent,
Fragment,
type KeyboardEvent,
useEffect,
useRef,
useState,
} from "react";
import { EDITORS, type EditorId } from "@acme/contracts";
import { buildBootstrapInput } from "../historyBootstrap";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
MODEL_OPTIONS,
REASONING_OPTIONS,
resolveModelSlug,
} from "../model-logic";
import {
derivePhase,
deriveTimelineEntries,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
formatTimestamp,
readNativeApi,
} from "../session-logic";
import { useStore } from "../store";
import ChatMarkdown from "./ChatMarkdown";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
return `${formatTimestamp(createdAt)} • ${duration}`;
}
const FILE_MANAGER_LABEL = navigator.platform.includes("Mac")
? "Finder"
: navigator.platform.includes("Win")
? "Explorer"
: "Files";
function editorLabel(editor: (typeof EDITORS)[number]): string {
return editor.command ? editor.label : FILE_MANAGER_LABEL;
}
const LAST_EDITOR_KEY = "codething:last-editor";
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
if (tone === "tool") return "text-muted-foreground/70";
if (tone === "thinking") return "text-muted-foreground/50";
return "text-muted-foreground/40";
}
interface PendingApprovalCard {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
type SessionContinuityState = "resumed" | "new" | "fallback_new";
interface EnsuredSessionInfo {
sessionId: string;
resolvedThreadId: string | null;
continuityState: SessionContinuityState;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asRecord(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {
const pending = new Map<string, PendingApprovalCard>();
const ordered = events.toReversed();
for (const event of ordered) {
if (event.method === "session/closed" || event.method === "session/exited") {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asRecord(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
export default function ChatView() {
const { state, dispatch } = useStore();
const api = readNativeApi();
const [prompt, setPrompt] = useState("");
const [isSending, setIsSending] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
const [isEditorMenuOpen, setIsEditorMenuOpen] = useState(false);
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
});
const [selectedEffort, setSelectedEffort] = useState<string>(DEFAULT_REASONING);
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>([]);
const [nowTick, setNowTick] = useState(() => Date.now());
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const modelMenuRef = useRef<HTMLDivElement>(null);
const editorMenuRef = useRef<HTMLDivElement>(null);
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const phase = derivePhase(activeThread?.session ?? null);
const isWorking = phase === "running" || isSending || isConnecting;
const nowIso = new Date(nowTick).toISOString();
const modelOptions = MODEL_OPTIONS;
const workLogEntries = deriveWorkLogEntries(activeThread?.events ?? [], undefined);
const pendingApprovals = derivePendingApprovals(activeThread?.events ?? []);
const assistantCompletionByItemId = (() => {
const map = new Map<string, string>();
const ordered = [...(activeThread?.events ?? [])].toReversed();
for (const event of ordered) {
if (event.method !== "item/completed") continue;
if (!event.itemId) continue;
map.set(event.itemId, event.createdAt);
}
return map;
})();
const timelineEntries = deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries);
const completionSummary = (() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (workLogEntries.length === 0) return null;
if (
typeof activeThread.latestTurnDurationMs === "number" &&
Number.isFinite(activeThread.latestTurnDurationMs) &&
activeThread.latestTurnDurationMs >= 0
) {
return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`;
}
const elapsed = formatElapsed(
activeThread.latestTurnStartedAt,
activeThread.latestTurnCompletedAt,
);
return elapsed ? `Worked for ${elapsed}` : null;
})();
const completionDividerBeforeEntryId = (() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (workLogEntries.length === 0) return null;
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
if (Number.isNaN(turnStartedAt)) return null;
const entry = timelineEntries.find((timelineEntry) => {
if (timelineEntry.kind !== "message") return false;
if (timelineEntry.message.role !== "assistant") return false;
const messageAt = Date.parse(timelineEntry.message.createdAt);
return !Number.isNaN(messageAt) && messageAt >= turnStartedAt;
});
return entry?.id ?? null;
})();
const runtimeSessionConfig =
state.runtimeMode === "full-access"
? ({
approvalPolicy: "never",
sandboxMode: "danger-full-access",
} as const)
: ({
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
} as const);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
if (!api) return;
const sessionIds = state.threads
.map((t) => t.session)
.filter((s): s is NonNullable<typeof s> => s !== null && s.status !== "closed")
.map((s) => s.sessionId);
if (sessionIds.length === 0) return;
setIsSwitchingRuntimeMode(true);
try {
await Promise.all(
sessionIds.map((id) => api.providers.stopSession({ sessionId: id }).catch(() => undefined)),
);
} finally {
setIsSwitchingRuntimeMode(false);
}
};
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messageCount]);
useEffect(() => {
if (phase !== "running") return;
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [phase, workLogCount]);
// Auto-resize textarea
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.style.height = "auto";
ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`;
}, [prompt]);
useEffect(() => {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 250);
return () => {
window.clearInterval(timer);
};
}, [phase]);
useEffect(() => {
if (!isModelMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!modelMenuRef.current) return;
if (event.target instanceof Node && !modelMenuRef.current.contains(event.target)) {
setIsModelMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isModelMenuOpen]);
useEffect(() => {
if (!isEditorMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!editorMenuRef.current) return;
if (event.target instanceof Node && !editorMenuRef.current.contains(event.target)) {
setIsEditorMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isEditorMenuOpen]);
// Cmd+O / Ctrl+O to open in last-used editor
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
if (api && activeProject) {
e.preventDefault();
void api.shell.openInEditor(activeProject.cwd, lastEditor);
}
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, lastEditor]);
const openInEditor = (editorId: EditorId) => {
if (!api || !activeProject) return;
void api.shell.openInEditor(activeProject.cwd, editorId);
setLastEditor(editorId);
localStorage.setItem(LAST_EDITOR_KEY, editorId);
setIsEditorMenuOpen(false);
};
const ensureSession = async (): Promise<EnsuredSessionInfo | null> => {
if (!api || !activeThread || !activeProject) return null;
if (
activeThread.session &&
activeThread.session.status !== "closed" &&
activeThread.session.status !== "error"
) {
const sessionThreadId = activeThread.session.threadId ?? null;
const continuityState: SessionContinuityState =
activeThread.codexThreadId === null
? "new"
: sessionThreadId === activeThread.codexThreadId
? "resumed"
: "fallback_new";
return {
sessionId: activeThread.session.sessionId,
resolvedThreadId: sessionThreadId,
continuityState,
} satisfies EnsuredSessionInfo;
}
const priorCodexThreadId = activeThread.codexThreadId;
setIsConnecting(true);
try {
const session = await api.providers.startSession({
provider: "codex",
cwd: activeProject.cwd || undefined,
model: selectedModel || undefined,
resumeThreadId: priorCodexThreadId ?? undefined,
approvalPolicy: runtimeSessionConfig.approvalPolicy,
sandboxMode: runtimeSessionConfig.sandboxMode,
});
dispatch({
type: "UPDATE_SESSION",
threadId: activeThread.id,
session,
});
const resolvedThreadId = session.threadId ?? null;
const continuityState: SessionContinuityState =
priorCodexThreadId === null
? "new"
: resolvedThreadId === priorCodexThreadId
? "resumed"
: "fallback_new";
return {
sessionId: session.sessionId,
resolvedThreadId,
continuityState,
};
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to connect.",
});
return null;
} finally {
setIsConnecting(false);
}
};
const onSend = async (e: FormEvent) => {
e.preventDefault();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed) return;
// Auto-title from first message
if (activeThread.messages.length === 0) {
const title = trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
title,
});
}
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: null,
});
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
});
const previousMessages = activeThread.messages;
setPrompt("");
const sessionInfo = await ensureSession();
if (!sessionInfo) return;
setIsSending(true);
try {
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
const input = shouldBootstrap
? buildBootstrapInput(previousMessages, trimmed, PROVIDER_SEND_TURN_MAX_INPUT_CHARS).text
: trimmed;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
input,
model: selectedModel || undefined,
effort: selectedEffort || undefined,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to send message.",
});
} finally {
setIsSending(false);
}
};
const onInterrupt = async () => {
if (!api || !activeThread?.session) return;
await api.providers.interruptTurn({
sessionId: activeThread.session.sessionId,
turnId: activeThread.session.activeTurnId,
});
};
const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeThread?.session) return;
setRespondingRequestIds((existing) =>
existing.includes(requestId) ? existing : [...existing, requestId],
);
try {
await api.providers.respondToRequest({
sessionId: activeThread.session.sessionId,
requestId,
decision,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
};
const onModelSelect = (model: string) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
setIsModelMenuOpen(false);
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
}
};
// Empty state: no active thread
if (!activeThread) {
return (
<div className="flex flex-1 flex-col bg-background text-muted-foreground/40">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-sm">Select a thread or create a new one to get started.</p>
</div>
</div>
</div>
);
}
return (
<div className="flex flex-1 flex-col bg-background">
{/* Top bar */}
<header className="drag-region flex items-center justify-between border-b border-border px-5 pt-[28px] pb-3">
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
{activeProject && (
<div className="relative" ref={editorMenuRef}>
<button
type="button"
className="rounded-md px-2 py-1 text-[10px] text-muted-foreground/40 transition-colors duration-150 hover:text-muted-foreground/60"
onClick={() => setIsEditorMenuOpen((v) => !v)}
>
Open in&hellip;
</button>
{isEditorMenuOpen && (
<div className="absolute right-0 top-full z-50 mt-1 min-w-[120px] rounded-md border border-border bg-popover py-1 shadow-xl">
{EDITORS.map((editor) => (
<button
key={editor.id}
type="button"
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-foreground hover:bg-accent"
onClick={() => openInEditor(editor.id)}
>
{editorLabel(editor)}
{editor.id === lastEditor && (
<kbd className="ml-auto text-[9px] text-muted-foreground/40">
{navigator.platform.includes("Mac") ? "\u2318O" : "Ctrl+O"}
</kbd>
)}
</button>
))}
</div>
)}
</div>
)}
{/* Diff toggle */}
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
state.diffOpen
? "bg-accent text-foreground"
: "text-muted-foreground/40 hover:text-muted-foreground/60"
}`}
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
Diff
</button>
</div>
</header>
{/* Error banner */}
{activeThread.error && (
<div className="mx-4 mt-3 rounded-lg border border-rose-400/20 bg-rose-900/20 px-3 py-2 text-xs text-rose-200">
{activeThread.error}
</div>
)}
{pendingApprovals.length > 0 && (
<div className="mx-4 mt-3 space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<div
key={approval.requestId}
className="rounded-lg border border-amber-300/20 bg-amber-500/[0.07] px-3 py-2"
>
<p className="text-xs font-medium text-amber-100">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</p>
{approval.detail && (
<p
className="mt-1 truncate font-mono text-[11px] text-amber-100/75"
title={approval.detail}
>
{approval.detail}
</p>
)}
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</button>
<button
type="button"
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</button>
<button
type="button"
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</button>
<button
type="button"
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</button>
</div>
</div>
);
})}
</div>
)}
{/* Messages */}
<div className="flex-1 overflow-y-auto px-5 py-4">
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => (
<Fragment key={timelineEntry.id}>
{timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
(completionDividerBeforeEntryId === timelineEntry.id ||
timelineEntries[index - 1]?.kind === "work") && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
{timelineEntry.kind === "work" ? (
<div className="flex items-start gap-2 py-0.5 pl-1.5">
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
>
{timelineEntry.entry.detail ? (
<>
{timelineEntry.entry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={timelineEntry.entry.detail}
>
{timelineEntry.entry.detail}
</span>
</>
) : (
timelineEntry.entry.label
)}
</p>
</div>
) : timelineEntry.message.role === "user" ? (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
) : (
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
{timelineEntry.message.streaming && (
<div className="pt-1.5">
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/[0.08] px-2 py-0.5 text-[10px] text-sky-100/90">
<span className="inline-flex gap-1">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:150ms]" />
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:300ms]" />
</span>
<span>Thinking</span>
</span>
</div>
)}
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
)}
</Fragment>
))}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</div>
{/* Input bar */}
<div className="px-5 pb-4 pt-2">
<form onSubmit={onSend} className="mx-auto max-w-3xl">
<div className="group rounded-[20px] border border-border bg-card transition-colors duration-200 focus-within:border-ring">
{/* Textarea area */}
<div className="px-4 pt-4 pb-2">
<textarea
ref={textareaRef}
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
rows={2}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onKeyDown={onKeyDown}
placeholder={
phase === "disconnected" ? "Ask for follow-up changes" : "Ask anything..."
}
disabled={isSending || isConnecting}
/>
</div>
{/* Bottom toolbar */}
<div className="flex items-center justify-between px-3 pb-3">
<div className="flex items-center gap-1">
{/* Model picker */}
<div className="relative" ref={modelMenuRef}>
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
onClick={() => setIsModelMenuOpen((open) => !open)}
>
<span className="max-w-[180px] truncate">{selectedModel}</span>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-50"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{isModelMenuOpen && (
<div className="absolute bottom-full left-0 z-20 mb-2 w-[320px] rounded-2xl border border-border bg-popover/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
<p className="px-2 py-1 text-[11px] text-muted-foreground/70">Select model</p>
<div className="max-h-72 overflow-y-auto">
{modelOptions.map((model) => {
const isSelected = model === selectedModel;
return (
<button
key={model}
type="button"
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left font-mono text-sm transition-colors duration-150 ${
isSelected
? "bg-accent text-foreground"
: "text-foreground/90 hover:bg-accent"
}`}
onClick={() => onModelSelect(model)}
>
<span className="truncate">{model}</span>
<span
className={`pt-0.5 text-sm ${
isSelected ? "text-foreground" : "text-transparent"
}`}
>
✓
</span>
</button>
);
})}
</div>
</div>
)}
</div>
{/* Divider */}
<div className="mx-0.5 h-4 w-px bg-border" />
{/* Reasoning effort */}
<label
className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
htmlFor="reasoning-effort"
>
<span>{selectedEffort.charAt(0).toUpperCase() + selectedEffort.slice(1)}</span>
<select
id="reasoning-effort"
className="absolute opacity-0 w-0 h-0"
value={selectedEffort}
onChange={(event) => setSelectedEffort(event.target.value)}
>
{REASONING_OPTIONS.map((effort) => (
<option key={effort} value={effort} className="bg-popover">
{effort}
{effort === DEFAULT_REASONING ? " (default)" : ""}
</option>
))}
</select>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-50"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</label>
{/* Divider */}
<div className="mx-0.5 h-4 w-px bg-border" />
{/* Runtime mode toggle */}
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
disabled={isSwitchingRuntimeMode}
onClick={() =>
void handleRuntimeModeChange(
state.runtimeMode === "full-access" ? "approval-required" : "full-access",
)
}
title={
state.runtimeMode === "full-access"
? "Full access — click to require approvals"
: "Approval required — click for full access"
}
>
{state.runtimeMode === "full-access" ? (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
width="10"
height="7"
rx="1.5"
stroke="currentColor"
strokeWidth="1.3"
/>
<path
d="M9.5 5.5V4a2.5 2.5 0 0 0-5 0"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
) : (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
width="10"
height="7"
rx="1.5"
stroke="currentColor"
strokeWidth="1.3"
/>
<path
d="M4.5 5.5V4a2.5 2.5 0 0 1 5 0v1.5"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
)}
<span>{state.runtimeMode === "full-access" ? "Full access" : "Supervised"}</span>
</button>
</div>
{/* Right side: send / stop button */}
<div className="flex items-center gap-2">
{phase === "running" ? (
<button
type="button"
className="flex h-8 w-8 items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105"
onClick={() => void onInterrupt()}
aria-label="Stop generation"
>
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="currentColor"
aria-hidden="true"
>
<rect x="2" y="2" width="8" height="8" rx="1.5" />
</svg>
</button>
) : (
<button
type="submit"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
disabled={isSending || isConnecting || !prompt.trim()}
aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
}
>
{isConnecting || isSending ? (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
className="animate-spin"
aria-hidden="true"
>
<circle
cx="7"
cy="7"
r="5.5"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeDasharray="20 12"
/>
</svg>
) : (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
aria-hidden="true"
>
<path
d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</button>
)}
</div>
</div>
</div>
</form>
</div>
</div>
);
}
@@ -0,0 +1,52 @@
import { useStore } from "../store";
export default function DiffPanel() {
const { dispatch } = useStore();
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div className="drag-region flex items-center justify-between border-b border-border px-4 pt-[28px] pb-3">
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
type="button"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
<div className="flex-1 overflow-y-auto p-4">
<div className="space-y-3">
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="mb-2 flex items-center gap-2">
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
M
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
</div>
<div className="space-y-0.5 font-mono text-[11px]">
<div className="text-red-400/60">- const oldValue = "hello";</div>
<div className="text-emerald-400/60">+ const newValue = "world";</div>
</div>
</div>
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="flex items-center gap-2">
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
A
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
</div>
</div>
</div>
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
Diff integration coming soon
</p>
</div>
</aside>
);
}
+330
View File
@@ -0,0 +1,330 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import type { Project } from "../types";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
if (status === "running") return "Working";
if (status === "connecting") return "Connecting";
return null;
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = readNativeApi();
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const handleAddProject = () => {
const cwd = newCwd.trim();
if (!cwd) return;
const name = cwd.split("/").findLast((segment) => segment.length > 0) ?? "project";
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
setNewCwd("");
setAddingProject(false);
};
const handleNewThread = (projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
setNewCwd(pickedPath);
} finally {
setIsPickingFolder(false);
}
};
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const isNewThreadShortcut =
event.metaKey &&
event.shiftKey &&
!event.ctrlKey &&
!event.altKey &&
event.key.toLowerCase() === "o";
if (!isNewThreadShortcut) return;
const target = event.target;
if (target instanceof HTMLElement) {
const tagName = target.tagName;
if (
target.isContentEditable ||
tagName === "INPUT" ||
tagName === "TEXTAREA" ||
tagName === "SELECT"
) {
return;
}
}
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [dispatch, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
{/* Drag region / traffic light space */}
<div className="drag-region h-[52px] shrink-0" />
{/* Branding */}
<div className="flex items-center gap-2 px-4 pb-4">
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
CT
</div>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
CodeThing
</span>
{state.runtimeError && (
<span className="rounded-full border border-rose-400/30 bg-rose-500/10 px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider text-rose-100">
Offline
</span>
)}
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
</div>
{/* New thread (global) */}
<div className="px-3 pb-3">
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={() => {
if (state.projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = state.projects[0];
if (firstProject) handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
New thread
</button>
</div>
{/* Project list */}
<nav className="flex-1 overflow-y-auto px-2">
{state.projects.map((project) => {
const threads = state.threads
.filter((t) => t.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
return (
<div key={project.id} className="mb-1">
{/* Project header */}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
>
<span className="text-[10px] text-muted-foreground/70">
{project.expanded ? "▼" : "▶"}
</span>
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
</button>
{/* Threads */}
{project.expanded && (
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusLabel(thread.session?.status);
return (
<button
key={thread.id}
type="button"
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() =>
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: thread.id,
})
}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{threadStatus && (
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
<span className="hidden xl:inline">{threadStatus}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</button>
);
})}
{/* New thread within project */}
<button
type="button"
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => handleNewThread(project.id)}
>
<span>+</span> New thread
</button>
</div>
)}
</div>
);
})}
{state.projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
Add one to get started.
</div>
)}
</nav>
{/* Add project form */}
{addingProject ? (
<div className="border-t border-border p-3">
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
Add project
</p>
<input
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
placeholder="/path/to/project"
value={newCwd}
onChange={(e) => setNewCwd(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAddProject();
if (e.key === "Escape") setAddingProject(false);
}}
/>
{api && (
<button
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-2">
<button
type="button"
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
onClick={handleAddProject}
>
Add
</button>
<button
type="button"
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
onClick={() => setAddingProject(false)}
>
Cancel
</button>
</div>
</div>
) : (
<div className="border-t border-border p-3">
<button
type="button"
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
onClick={() => setAddingProject(true)}
>
+ Add project
</button>
</div>
)}
</aside>
);
}
@@ -1,23 +1,20 @@
import { MessageId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { buildBootstrapInput } from "./historyBootstrap";
const messageId = (value: string) => MessageId.makeUnsafe(value);
describe("buildBootstrapInput", () => {
it("includes full transcript when under budget", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-1"),
id: "u-1",
role: "user",
text: "hello",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: messageId("a-1"),
id: "a-1",
role: "assistant",
text: "world",
createdAt: "2026-02-09T00:00:01.000Z",
@@ -41,21 +38,21 @@ describe("buildBootstrapInput", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-1"),
id: "u-1",
role: "user",
text: "first question with details",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: messageId("a-1"),
id: "a-1",
role: "assistant",
text: "first answer with details",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
{
id: messageId("u-2"),
id: "u-2",
role: "user",
text: "second question with details",
createdAt: "2026-02-09T00:00:02.000Z",
@@ -78,7 +75,7 @@ describe("buildBootstrapInput", () => {
const result = buildBootstrapInput(
[
{
id: messageId("u-1"),
id: "u-1",
role: "user",
text: "old context",
createdAt: "2026-02-09T00:00:00.000Z",
@@ -94,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: messageId("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,8 +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
// oxlint-disable-next-line no-unused-expressions
document.documentElement.offsetHeight;
void document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
@@ -76,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,29 +161,12 @@
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;
}
html,
body,
#root {
height: 100%;
width: 100%;
max-width: 100%;
overflow-y: hidden;
overflow-x: hidden;
overflow-x: clip;
overscroll-behavior-y: none;
}
body::after {
content: "";
position: fixed;
@@ -202,30 +224,6 @@ input {
background: rgba(255, 255, 255, 0.18);
}
.turn-chip-strip {
scrollbar-width: none;
-ms-overflow-style: none;
overscroll-behavior-x: contain;
}
.turn-chip-strip::-webkit-scrollbar {
display: none;
}
/* 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;
@@ -241,9 +239,7 @@ label:has(> select#reasoning-effort) select {
/* Chat markdown rendering */
.chat-markdown {
min-width: 0;
overflow-wrap: anywhere;
word-break: break-word;
}
.chat-markdown > :first-child {
@@ -294,11 +290,9 @@ label:has(> select#reasoning-effort) select {
background: var(--muted);
padding: 0.1rem 0.35rem;
color: var(--foreground);
font-size: 0.75rem;
}
.chat-markdown pre {
max-width: 100%;
overflow-x: auto;
border: 1px solid var(--border);
border-radius: 0.75rem;
@@ -311,7 +305,6 @@ label:has(> select#reasoning-effort) select {
background: transparent;
padding: 0;
line-height: 1.5;
font-size: 0.875rem;
}
.chat-markdown table {
+12
View File
@@ -0,0 +1,12 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "highlight.js/styles/github-dark.css";
import App from "./App";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL, normalizeModelSlug, resolveModelSlug } from "./model-logic";
describe("normalizeModelSlug", () => {
it("maps 5.3 aliases to canonical codex slug", () => {
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("preserves non-aliased slugs", () => {
expect(normalizeModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
});
it("returns null for empty input", () => {
expect(normalizeModelSlug("")).toBeNull();
expect(normalizeModelSlug(" ")).toBeNull();
expect(normalizeModelSlug(null)).toBeNull();
expect(normalizeModelSlug(undefined)).toBeNull();
});
});
describe("resolveModelSlug", () => {
it("falls back to default for unknown models", () => {
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
});
it("resolves supported hard-coded models", () => {
expect(resolveModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(resolveModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(resolveModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
+9
View File
@@ -0,0 +1,9 @@
export {
DEFAULT_MODEL,
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@acme/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
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,
};
}
+523
View File
@@ -0,0 +1,523 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
} from "./session-logic";
import type { ChatMessage } from "./types";
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-08T10:00:00.000Z",
method: "noop",
...overrides,
};
}
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-08T09:59:00.000Z",
updatedAt: "2026-02-08T09:59:00.000Z",
...overrides,
};
}
describe("deriveTimelineEntries", () => {
it("interleaves messages and work entries by timestamp", () => {
const messages: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:05:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:02:00.000Z",
tone: "tool",
},
{
id: "w-2",
label: "Preamble",
createdAt: "2026-02-08T10:03:00.000Z",
tone: "thinking",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual([
"message:m-user",
"work:w-1",
"work:w-2",
"message:m-assistant",
]);
});
it("prefers work entries when timestamps are equal", () => {
const messages: ChatMessage[] = [
{
id: "m-1",
role: "assistant",
text: "Done",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:00:00.000Z",
tone: "tool",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
});
});
describe("deriveWorkLogEntries", () => {
it("drops preamble/work events from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-1",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { item: { type: "preamble", text: "thinking" } },
}),
makeEvent({
id: "evt-2",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "work", text: "planning" } },
}),
makeEvent({
id: "evt-3",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
});
it("logs turn completion with elapsed time", () => {
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: "completed" } },
}),
],
"turn-1",
);
expect(entries[0]?.label).toBe("Turn complete in 10s");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-summary-part",
method: "item/reasoning/summaryPartAdded",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-summary-delta",
method: "item/reasoning/summaryTextDelta",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
}),
makeEvent({
id: "evt-agent-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
},
}),
makeEvent({
id: "evt-agent-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
item: {
id: "item-msg",
type: "agentMessage",
text: "Done response",
},
},
}),
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", command: "ls -la" },
},
}),
makeEvent({
id: "evt-tool-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:06.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:08.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
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", () => {
const longCommand =
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
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", command: longCommand },
},
}),
],
"turn-1",
);
expect(entries[0]?.detail).toBe(longCommand);
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-1-tool",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
makeEvent({
id: "evt-turn-2-tool",
method: "item/started",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "pwd" } },
}),
],
undefined,
);
expect(entries).toHaveLength(2);
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "thread/started",
createdAt: "2026-02-08T10:01:00.000Z",
payload: { thread: { id: "thread-1" } },
}),
);
expect(next.threadId).toBe("thread-1");
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("moves to running and records active turn on turn start", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:02:00.000Z",
}),
);
expect(next.status).toBe("running");
expect(next.activeTurnId).toBe("turn-1");
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
});
it("returns to ready and clears active turn on successful completion", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
lastError: "older error",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
);
expect(next.status).toBe("ready");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("older error");
});
it("marks session as error when turn fails", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: {
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
},
}),
);
expect(next.status).toBe("error");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("boom");
});
it("moves to error on runtime error events", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
kind: "error",
method: "runtime/error",
createdAt: "2026-02-08T10:04:00.000Z",
message: "runtime failure",
}),
);
expect(next.status).toBe("error");
expect(next.lastError).toBe("runtime failure");
});
it("closes session on close lifecycle events", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "session/closed",
createdAt: "2026-02-08T10:05:00.000Z",
message: "closed",
}),
);
expect(next.status).toBe("closed");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("closed");
});
});
describe("applyEventToMessages", () => {
it("handles start/delta/completed flow for assistant messages", () => {
const activeAssistantItemRef = { current: null as string | null };
const started = applyEventToMessages(
[],
makeEvent({
method: "item/started",
createdAt: "2026-02-08T10:00:00.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello",
},
},
}),
activeAssistantItemRef,
);
expect(started).toEqual([
{
id: "item-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
]);
expect(activeAssistantItemRef.current).toBe("item-1");
const withDelta = applyEventToMessages(
started,
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-1",
textDelta: " world",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.text).toBe("Hello world");
expect(withDelta[0]?.streaming).toBe(true);
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello world!",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Hello world!");
expect(completed[0]?.streaming).toBe(false);
expect(activeAssistantItemRef.current).toBeNull();
});
it("supports out-of-order delta before started/completed", () => {
const activeAssistantItemRef = { current: null as string | null };
const withDelta = applyEventToMessages(
[],
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-2",
textDelta: "Partial",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.id).toBe("item-2");
expect(withDelta[0]?.text).toBe("Partial");
expect(withDelta[0]?.streaming).toBe(true);
expect(activeAssistantItemRef.current).toBe("item-2");
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-2",
type: "agentMessage",
text: "Partial + final",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Partial + final");
expect(completed[0]?.streaming).toBe(false);
});
it("clears all streaming flags when turn completes", () => {
const previous: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Typing",
createdAt: "2026-02-08T10:00:01.000Z",
streaming: true,
},
];
const next = applyEventToMessages(
previous,
makeEvent({
method: "turn/completed",
}),
{ current: null },
);
expect(next.every((entry) => entry.streaming === false)).toBe(true);
});
});
+567
View File
@@ -0,0 +1,567 @@
import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { getOrCreateWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
label: string;
available: boolean;
}> = [
{ value: "codex", label: "Codex", available: true },
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
export function readNativeApi() {
if (typeof window === "undefined") return undefined;
return window.nativeApi ?? getOrCreateWsNativeApi();
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
return null;
}
return formatDuration(endedAt - startedAt);
}
export interface WorkLogEntry {
id: string;
createdAt: string;
label: string;
detail?: string;
tone: "thinking" | "tool" | "info" | "error";
}
export type TimelineEntry =
| {
id: string;
kind: "message";
createdAt: string;
message: ChatMessage;
}
| {
id: string;
kind: "work";
createdAt: string;
entry: WorkLogEntry;
};
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._/-]/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
return type === "work" || type.startsWith("work ");
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
}
function itemTypeMeta(type: string): {
label: string;
tone: WorkLogEntry["tone"];
} {
if (type.includes("command")) {
return { label: "Command run", tone: "tool" };
}
if (type.includes("file change")) {
return { label: "File change", tone: "tool" };
}
if (type.includes("tool")) {
return { label: "Tool call", tone: "tool" };
}
return { label: "Work item", tone: "info" };
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.command),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
];
for (const candidate of candidates) {
const detail = normalizeDetail(candidate);
if (detail) return detail;
}
return undefined;
}
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
return null;
}
if (!shouldShowItemLifecycle(normalizedType)) {
return null;
}
const meta = itemTypeMeta(normalizedType);
const isStarted = event.method === "item/started";
const isCompleted = event.method === "item/completed";
if (!isStarted && !isCompleted) {
return null;
}
const label = isCompleted ? `${meta.label} complete` : meta.label;
const detail = extractDetail(payload, item);
return {
id: event.id,
createdAt: event.createdAt,
label,
...(detail ? { detail } : {}),
tone: meta.tone,
};
}
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "request") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method.includes("commandExecution")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Command approval requested",
tone: "tool",
};
}
if (event.method.includes("fileChange")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "File-change approval requested",
tone: "tool",
};
}
if (event.method.includes("requestUserInput")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Tool requested user input",
tone: "tool",
};
}
return {
id: event.id,
createdAt: event.createdAt,
label: `Request: ${event.method}`,
tone: "info",
};
}
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;
if (event.method === "turn/started") {
return null;
}
if (event.method === "thread/started") return null;
if (event.method === "turn/completed") {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
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:
status === "failed"
? "Turn failed"
: durationMs !== undefined
? `Turn complete in ${formatDuration(durationMs)}`
: "Turn complete",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: status === "failed" ? "error" : "info",
};
}
const lifecycleEntry = entryFromItemLifecycle(event);
if (lifecycleEntry) return lifecycleEntry;
if (event.method.startsWith("item/")) return null;
return null;
}
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "error") return null;
if (shouldDropMethod(event.method)) return null;
const detail = normalizeDetail(event.message);
return {
id: event.id,
createdAt: event.createdAt,
label: "Runtime error",
...(detail ? { detail } : {}),
tone: "error",
};
}
function eventTurnId(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return event.turnId ?? asString(turn?.id);
}
export function deriveWorkLogEntries(
events: ProviderEvent[],
turnId: string | undefined,
): WorkLogEntry[] {
const ordered = [...events].toReversed();
const entries: WorkLogEntry[] = [];
const turnStartedAtIso = turnId
? ordered.find((event) => {
if (event.method !== "turn/started") return false;
return eventTurnId(event) === turnId;
})?.createdAt
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
for (const event of ordered) {
if (turnId) {
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
continue;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
continue;
}
}
}
const fromRequest = entryFromRequest(event);
if (fromRequest) {
entries.push(fromRequest);
continue;
}
const fromNotification = entryFromNotification(event, turnStartedAt);
if (fromNotification) {
entries.push(fromNotification);
continue;
}
const fromError = entryFromError(event);
if (fromError) {
entries.push(fromError);
}
}
return entries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
while (messageIndex < messages.length || workIndex < workEntries.length) {
const message = messages[messageIndex];
const workEntry = workEntries[workIndex];
if (!message && workEntry) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
if (!workEntry && message) {
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
continue;
}
if (!message || !workEntry) {
break;
}
const messageAt = toTimestamp(message.createdAt);
const workAt = toTimestamp(workEntry.createdAt);
if (workAt <= messageAt) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
}
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
if (!session || session.status === "closed") return "disconnected";
if (session.status === "connecting") return "connecting";
if (session.status === "running") return "running";
return "ready";
}
export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return {
...previous,
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
export function applyEventToMessages(
previous: ChatMessage[],
event: ProviderEvent,
activeAssistantItemRef: { current: string | null },
): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
activeAssistantItemRef.current = itemId;
const seedText = asString(item?.text) ?? "";
const filtered = previous.filter((entry) => entry.id !== itemId);
return [
...filtered,
{
id: itemId,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
streaming: true,
},
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return previous;
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
activeAssistantItemRef.current = itemId;
return [
...previous,
{
id: itemId,
role: "assistant",
text: delta,
createdAt: event.createdAt,
streaming: true,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: `${existing.text}${delta}`,
streaming: true,
};
return updated;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
const fullText = asString(item?.text);
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
return [
...previous,
{
id: itemId,
role: "assistant",
text: fullText ?? "",
createdAt: event.createdAt,
streaming: false,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: fullText ?? existing.text,
streaming: false,
};
if (activeAssistantItemRef.current === itemId) {
activeAssistantItemRef.current = null;
}
return updated;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return previous;
}
+181
View File
@@ -0,0 +1,181 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import type { Thread } from "./types";
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-09T00:00:01.000Z",
method: "thread/started",
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-local-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
session: makeSession(),
messages: [],
events: [],
error: null,
createdAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeState(thread: Thread): AppState {
return {
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: thread.id,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
}
describe("store reducer thread continuity", () => {
it("bootstraps project and active thread from runtime response", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const session = makeSession({
sessionId: "sess-bootstrap",
threadId: "thr-bootstrap",
});
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session,
},
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.cwd).toBe("/workspace");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.session?.sessionId).toBe("sess-bootstrap");
expect(next.activeThreadId).toBe(next.threads[0]?.id ?? null);
});
it("surfaces bootstrap errors on the active thread", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session: makeSession({
sessionId: "sess-bootstrap-error",
status: "error",
}),
bootstrapError: "Timed out waiting for initialize.",
},
});
expect(next.threads[0]?.error).toBe("Timed out waiting for initialize.");
});
it("stores runtime connection errors separately from thread errors", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_RUNTIME_ERROR",
error: "Connection refused",
});
expect(next.runtimeError).toBe("Connection refused");
expect(next.threads[0]?.error).toBeNull();
});
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
makeThread({
session: null,
}),
);
const next = reducer(state, {
type: "UPDATE_SESSION",
threadId: "thread-local-1",
session: makeSession({ threadId: "thr_123" }),
});
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
payload: { thread: { id: "thr_backfilled" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
});
it("surfaces thread id mismatches without overwriting stored identity", () => {
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/started",
threadId: "thr_unexpected",
payload: { turn: { id: "turn-1" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_expected");
expect(next.threads[0]?.error).toContain("Thread identity mismatch");
});
});
+410
View File
@@ -0,0 +1,410 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import type { AppBootstrapResult, ProviderEvent, ProviderSession } from "@acme/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import { DEFAULT_RUNTIME_MODE, type Project, type RuntimeMode, type Thread } from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "SET_RUNTIME_ERROR"; error: string | null }
| { type: "BOOTSTRAP_FROM_SERVER"; bootstrap: AppBootstrapResult };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
runtimeError: string | null;
}
const PERSISTED_STATE_KEY = "codething:renderer-state:v4";
const LEGACY_PERSISTED_STATE_KEYS = [
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
const initialState: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
runtimeError: null,
};
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const [legacyV3Key, legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
const rawLegacyV3 = window.localStorage.getItem(legacyV3Key);
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
const raw = rawCurrent ?? rawLegacyV3 ?? rawLegacyV2 ?? rawLegacyV1;
if (!raw) return initialState;
const hydrated = hydratePersistedState(
raw,
!rawCurrent && !rawLegacyV3 && !rawLegacyV2 && Boolean(rawLegacyV1),
);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false, runtimeError: null };
} catch {
return initialState;
}
}
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
function updateThread(
threads: Thread[],
threadId: string,
updater: (t: Thread) => Thread,
): Thread[] {
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
function getEventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.id);
}
function getEventThreadId(event: ProviderEvent): string | undefined {
if (event.threadId) return event.threadId;
const payload = asObject(event.payload);
return asString(payload?.threadId) ?? asString(asObject(payload?.thread)?.id);
}
function durationMs(startIso: string, endIso: string): number | undefined {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
return undefined;
}
return end - start;
}
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
latestTurnStartedAt: event.createdAt,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
};
}
if (event.method === "turn/completed") {
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
const startedAt =
completedTurnId && completedTurnId === thread.latestTurnId
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
latestTurnCompletedAt: event.createdAt,
latestTurnDurationMs: elapsed,
};
}
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "ADD_PROJECT":
return {
...state,
projects: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
},
],
};
case "TOGGLE_PROJECT":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "ADD_THREAD":
return {
...state,
threads: [
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
},
],
activeThreadId: action.thread.id,
};
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
return {
...state,
threads: updateThread(state.threads, target.id, (t) => ({
...t,
...(() => {
const eventThreadId = getEventThreadId(event);
const hasThreadMismatch =
t.codexThreadId !== null &&
eventThreadId !== undefined &&
eventThreadId !== t.codexThreadId;
const threadMismatchError = hasThreadMismatch
? `Thread identity mismatch: expected ${t.codexThreadId}, received ${eventThreadId}.`
: null;
return {
codexThreadId: t.codexThreadId ?? eventThreadId ?? null,
error:
threadMismatchError ??
(event.kind === "error" && event.message ? event.message : t.error),
};
})(),
session: t.session ? evolveSession(t.session, event) : t.session,
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
events: [event, ...t.events],
...updateTurnFields(t, event),
})),
};
}
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
codexThreadId: action.session.threadId ?? t.codexThreadId,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
id: action.id,
role: "user" as const,
text: action.text,
createdAt: new Date().toISOString(),
streaming: false,
},
],
})),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
case "SET_RUNTIME_ERROR":
return {
...state,
runtimeError: action.error,
};
case "BOOTSTRAP_FROM_SERVER": {
const { bootstrap } = action;
const existingProject = state.projects.find((project) => project.cwd === bootstrap.launchCwd);
const projectId = existingProject?.id ?? crypto.randomUUID();
const project =
existingProject ??
({
id: projectId,
name: bootstrap.projectName,
cwd: bootstrap.launchCwd,
model: resolveModelSlug(bootstrap.model),
expanded: true,
} satisfies Project);
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
const existingThread =
state.threads.find((thread) => thread.session?.sessionId === bootstrap.session.sessionId) ??
projectThreads.find(
(thread) =>
bootstrap.session.threadId !== undefined &&
thread.codexThreadId === bootstrap.session.threadId,
) ??
projectThreads[0];
const activeThreadId = existingThread?.id ?? crypto.randomUUID();
const thread =
existingThread ??
({
id: activeThreadId,
codexThreadId: bootstrap.session.threadId ?? null,
projectId,
title: "New thread",
model: resolveModelSlug(bootstrap.model),
session: bootstrap.session,
messages: [],
events: [],
error: bootstrap.bootstrapError ?? null,
createdAt: new Date().toISOString(),
} satisfies Thread);
return {
...state,
projects: existingProject
? state.projects.map((entry) =>
entry.id === existingProject.id
? {
...entry,
model: resolveModelSlug(bootstrap.model),
}
: entry,
)
: [project, ...state.projects],
threads: state.threads
.map((entry) =>
entry.id === thread.id
? {
...entry,
session: bootstrap.session,
codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId,
error: bootstrap.bootstrapError ?? entry.error,
}
: entry,
)
.concat(existingThread ? [] : [thread]),
activeThreadId,
runtimeError: null,
};
}
default:
return state;
}
}
// ── Context ──────────────────────────────────────────────────────────
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
}
+38
View File
@@ -0,0 +1,38 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
createdAt: string;
streaming: boolean;
}
export interface Project {
id: string;
name: string;
cwd: string;
model: string;
expanded: boolean;
}
export interface Thread {
id: string;
codexThreadId: string | null;
projectId: string;
title: string;
model: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
}
@@ -1,10 +1,9 @@
/// <reference types="vite/client" />
import type { NativeApi, DesktopBridge } from "@t3tools/contracts";
import type { NativeApi } from "@acme/contracts";
declare global {
interface Window {
nativeApi?: NativeApi;
desktopBridge?: DesktopBridge;
}
}
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;
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"jsx": "react-jsx",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"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,
},
});
@@ -1,367 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
}
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
return true;
} catch {
return false;
}
}
export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
function waitFor<A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
return read.pipe(
Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
Effect.retry({
schedule: retrySchedule,
times: maxRetries,
while: (error) => error === RETRY_SIGNAL,
}),
Effect.mapError((error) =>
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
),
Effect.orDie,
);
}
export interface OrchestrationIntegrationHarness {
readonly rootDir: string;
readonly workspaceDir: string;
readonly dbPath: string;
readonly adapterHarness: TestProviderAdapterHarness;
readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService["Service"];
readonly checkpointStore: CheckpointStore["Service"];
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
readonly waitForThread: (
threadId: string,
predicate: (thread: OrchestrationThread) => boolean,
timeoutMs?: number,
) => Effect.Effect<OrchestrationThread, never>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
readonly waitForPendingApproval: (
requestId: string,
predicate: (row: {
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}) => boolean,
timeoutMs?: number,
) => Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
readonly dispose: Effect.Effect<void, never>;
}
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const adapterHarness = yield* makeTestProviderAdapterHarness;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(adapterHarness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
providerLayer,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
const engine = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationEngineService)),
);
const reactor = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationReactor)),
);
const snapshotQuery = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
);
const providerService = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProviderService)),
);
const checkpointStore = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(CheckpointStore)),
);
const checkpointRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
);
const pendingApprovalRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
);
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
predicate,
timeoutMs,
) =>
waitFor(
snapshotQuery
.getSnapshot()
.pipe(
Effect.map(
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
),
),
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
`projected thread '${threadId}'`,
timeoutMs,
) as Effect.Effect<OrchestrationThread, never>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
timeoutMs,
) =>
waitFor(
Stream.runCollect(engine.readEvents(0)).pipe(
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
),
(events) => events.some(predicate),
"domain event",
timeoutMs,
);
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
requestId,
predicate,
timeoutMs,
) =>
waitFor(
pendingApprovalRepository
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
.pipe(
Effect.map((row) =>
Option.match(row, {
onNone: () => null,
onSome: (value) => ({
status: value.status,
decision: value.decision,
resolvedAt: value.resolvedAt,
}),
}),
),
),
(
row,
): row is {
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
} => row !== null && predicate(row),
`pending approval '${requestId}'`,
timeoutMs,
) as Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
let disposed = false;
const dispose = Effect.gen(function* () {
if (disposed) {
return;
}
disposed = true;
const shutdown = Effect.gen(function* () {
const stopAllExit = yield* Effect.exit(
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
);
const closeScopeExit = yield* Effect.exit(
Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
);
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(stopAllExit)
? stopAllExit.cause
: Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
if (failureCause) {
return yield* Effect.failCause(failureCause);
}
});
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
rootDir,
workspaceDir,
dbPath,
adapterHarness,
engine,
snapshotQuery,
providerService,
checkpointStore,
checkpointRepository,
pendingApprovalRepository,
waitForThread,
waitForDomainEvent,
waitForPendingApproval,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -1,368 +0,0 @@
import { randomUUID } from "node:crypto";
import {
ApprovalRequestId,
EventId,
ProviderApprovalDecision,
ProviderRuntimeEvent,
ProviderSession,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../src/provider/Errors.ts";
import type {
ProviderAdapterShape,
ProviderThreadSnapshot,
ProviderThreadTurnSnapshot,
} from "../src/provider/Services/ProviderAdapter.ts";
export interface TestTurnResponse {
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
readonly mutateWorkspace?: (input: {
readonly cwd: string;
readonly turnCount: number;
}) => Effect.Effect<void, never>;
}
interface SessionState {
readonly session: ProviderSession;
snapshot: ProviderThreadSnapshot;
turnCount: number;
readonly queuedResponses: Array<TestTurnResponse>;
readonly rollbackCalls: Array<number>;
}
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly queueTurnResponse: (
sessionId: string,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
readonly sessionId: ProviderSessionId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>;
}
const PROVIDER = "codex" as const;
function nowIso(): string {
return new Date().toISOString();
}
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
sessionId,
});
}
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(sessionId));
}
export const makeTestProviderAdapterHarness = Effect.gen(function* () {
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<string, SessionState>();
const queuedResponsesForNextSession: TestTurnResponse[] = [];
const approvalResponsesBySession = new Map<
string,
Array<{
readonly sessionId: ProviderSessionId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
const createdAt = nowIso();
const session: ProviderSession = {
sessionId,
provider: PROVIDER,
status: "ready",
threadId,
cwd: input.cwd,
createdAt,
updatedAt: createdAt,
};
sessions.set(sessionId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.sessionId);
if (!state) {
return yield* missingSessionEffect(input.sessionId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: `No queued turn response for session ${input.sessionId}.`,
});
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider: PROVIDER,
sessionId: input.sessionId,
createdAt: nowIso(),
};
if (Object.hasOwn(rawEvent, "threadId")) {
rawEvent.threadId = state.snapshot.threadId;
}
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
if (runtimeEvent.type === "message.delta") {
assistantDeltas.push(runtimeEvent.delta);
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider: PROVIDER,
sessionId: input.sessionId,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
status: "completed",
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
sessionId,
_turnId,
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
sessionId,
requestId,
decision,
) =>
sessions.has(sessionId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(sessionId) ?? [];
existing.push({
sessionId,
requestId,
decision,
});
approvalResponsesBySession.set(sessionId, existing);
})
: missingSessionEffect(sessionId);
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
Effect.sync(() => {
sessions.delete(sessionId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
Effect.succeed(sessions.has(sessionId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
const state = sessions.get(sessionId);
if (!state) {
return missingSessionEffect(sessionId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
sessionId,
numTurns,
) => {
const state = sessions.get(sessionId);
if (!state) {
return missingSessionEffect(sessionId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider: PROVIDER,
startSession,
sendTurn,
interruptTurn,
respondToRequest,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const queueTurnResponse = (
sessionId: string,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(sessionId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(sessionId)),
),
);
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
const state = sessions.get(sessionId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getApprovalResponses = (
sessionId: string,
): ReadonlyArray<{
readonly sessionId: ProviderSessionId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(sessionId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
queueTurnResponse,
queueTurnResponseForNextSession,
getRollbackCalls,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -1,138 +0,0 @@
import {
ApprovalRequestId,
EventId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
const PROVIDER = "codex" as const;
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
function baseEvent(
eventId: string,
createdAt: string,
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.makeUnsafe(eventId),
provider: PROVIDER,
sessionId: SESSION_ID,
createdAt,
};
}
export const codexTurnTextFixture = [
{
type: "turn.started",
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
},
{
type: "message.delta",
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "I will make a small update.\n",
},
{
type: "message.delta",
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Done.\n",
},
{
type: "turn.completed",
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
export const codexTurnToolFixture = [
{
type: "turn.started",
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
},
{
type: "tool.started",
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
toolKind: "command",
title: "Command run",
detail: "echo integration",
},
{
type: "tool.completed",
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
toolKind: "command",
title: "Command run",
detail: "echo integration",
},
{
type: "message.delta",
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Applied the requested edit.\n",
},
{
type: "turn.completed",
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
export const codexTurnApprovalFixture = [
{
type: "turn.started",
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
},
{
type: "approval.requested",
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
requestKind: "command",
detail: "Please approve command",
},
{
type: "approval.resolved",
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
requestKind: "command",
decision: "accept",
},
{
type: "message.delta",
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Approval received and command executed.\n",
},
{
type: "turn.completed",
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
@@ -1,760 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import {
ApprovalRequestId,
CommandId,
EventId,
MessageId,
ProjectId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Exit, Option } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import {
gitRefExists,
gitShowFileAtRef,
makeOrchestrationIntegrationHarness,
type OrchestrationIntegrationHarness,
} from "./OrchestrationEngineHarness.integration.ts";
import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProviderSessionId = (value: string): ProviderSessionId =>
ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
function nowIso() {
return new Date().toISOString();
}
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
while (true) {
const value = read();
if (predicate(value)) {
return value;
}
if (Date.now() >= deadline) {
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
}
yield* sleep(10);
}
});
}
function runtimeBase(eventId: string, createdAt: string) {
return {
eventId: asEventId(eventId),
provider: "codex" as const,
sessionId: FIXTURE_SESSION_ID,
createdAt,
};
}
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness,
use,
(harness) => harness.dispose,
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5-codex",
createdAt,
});
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: harness.workspaceDir,
createdAt,
});
});
const startTurn = (input: {
readonly harness: OrchestrationIntegrationHarness;
readonly commandId: string;
readonly messageId: string;
readonly text: string;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe(input.commandId),
threadId: THREAD_ID,
message: {
messageId: asMessageId(input.messageId),
role: "user",
text: input.text,
attachments: [],
},
createdAt: nowIso(),
});
it.live("always removes integration temp dirs when shutdown fails", () =>
Effect.gen(function* () {
const harness = yield* makeOrchestrationIntegrationHarness;
const rootDir = harness.rootDir;
const originalStopAll = harness.providerService.stopAll.bind(harness.providerService);
(
harness.providerService as unknown as {
stopAll: typeof harness.providerService.stopAll;
}
).stopAll = () => originalStopAll().pipe(Effect.andThen(Effect.fail(new Error("boom"))));
const disposeExit = yield* Effect.exit(harness.dispose);
assert.equal(Exit.isFailure(disposeExit), true);
assert.equal(fs.existsSync(rootDir), false);
}),
);
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
const turnResponse: TestTurnResponse = {
events: [
{
type: "turn.started",
...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Single turn response.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
};
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
yield* startTurn({
harness,
commandId: "cmd-turn-start-single",
messageId: "msg-user-single",
text: "Say hello",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.streaming === false,
) &&
entry.checkpoints.length === 1,
);
assert.equal(thread.checkpoints[0]?.status, "ready");
assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
assert.equal(checkpointRows[0]?.checkpointTurnCount, 1);
assert.equal(checkpointRows[0]?.status, "ready");
assert.deepEqual(checkpointRows[0]?.files, []);
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-diff-completed");
const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);
const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);
assert.equal(gitRefExists(harness.workspaceDir, ref0), true);
assert.equal(gitRefExists(harness.workspaceDir, ref1), true);
assert.equal(gitShowFileAtRef(harness.workspaceDir, ref0, "README.md"), "v1\n");
assert.equal(gitShowFileAtRef(harness.workspaceDir, ref1, "README.md"), "v1\n");
}),
),
);
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-multi-1",
messageId: "msg-user-multi-1",
text: "Make first edit",
});
const firstTurnThread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.checkpoints.length === 1 && entry.session?.providerSessionId !== null,
);
const sessionId = firstTurnThread.session?.providerSessionId;
assert.equal(sessionId !== null, true);
if (!sessionId) {
return;
}
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
events: [
{
type: "turn.started",
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-multi-2",
messageId: "msg-user-multi-2",
text: "Make second edit",
});
const secondTurnThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
);
const secondCheckpoint = secondTurnThread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === 2,
);
assert.equal(
secondCheckpoint?.files.some((file) => file.path === "README.md"),
true,
);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.deepEqual(
checkpointRows.map((row) => row.checkpointTurnCount),
[1, 2],
);
const incrementalDiff = yield* harness.checkpointStore.diffCheckpoints({
cwd: harness.workspaceDir,
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
});
assert.equal(incrementalDiff.includes("README.md"), true);
const fullDiff = yield* harness.checkpointStore.diffCheckpoints({
cwd: harness.workspaceDir,
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
});
assert.equal(fullDiff.includes("README.md"), true);
assert.equal(
gitShowFileAtRef(
harness.workspaceDir,
checkpointRefForThreadTurn(THREAD_ID, 1),
"README.md",
),
"v2\n",
);
assert.equal(
gitShowFileAtRef(
harness.workspaceDir,
checkpointRefForThreadTurn(THREAD_ID, 2),
"README.md",
),
"v3\n",
);
}),
),
);
it.live("tracks approval requests and resolves pending approvals on user response", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve command execution",
},
{
type: "turn.completed",
...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-approval",
messageId: "msg-user-approval",
text: "Run command needing approval",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(
thread.activities.some((activity) => activity.kind === "approval.requested"),
true,
);
const pendingRow = yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "pending" && row.decision === null,
);
assert.equal(pendingRow.status, "pending");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
const resolvedRow = yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
assert.equal(resolvedRow.status, "resolved");
assert.equal(resolvedRow.decision, "accept");
const providerSessionId = thread.session?.providerSessionId ?? "test-session-1";
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness.getApprovalResponses(providerSessionId),
(responses) => responses.length === 1,
"provider approval response",
);
assert.equal(approvalResponses.length, 1);
assert.equal(approvalResponses[0]?.requestId, "req-approval-1");
assert.equal(approvalResponses[0]?.decision, "accept");
}),
),
);
it.live("records failed turn runtime state and checkpoint status as error", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Partial output before failure.\n",
},
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
message: "Sandbox command failed.",
},
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "failed",
errorMessage: "Sandbox command failed.",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-failure",
messageId: "msg-user-failure",
text: "Run risky command",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "error" &&
entry.session?.lastError === "Sandbox command failed." &&
entry.activities.some((activity) => activity.kind === "runtime.error") &&
entry.checkpoints.length === 1,
);
assert.equal(thread.session?.status, "error");
assert.equal(thread.checkpoints[0]?.status, "error");
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
threadId: THREAD_ID,
checkpointTurnCount: 1,
});
assert.equal(Option.isSome(checkpointRow), true);
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
);
it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
});
const firstTurnThread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.providerSessionId !== null && entry.checkpoints.length === 1,
);
const sessionId = firstTurnThread.session?.providerSessionId;
assert.equal(sessionId !== null, true);
if (!sessionId) {
return;
}
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
threadId: FIXTURE_THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.deepEqual(
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
assert.equal(
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
false,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
),
true,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
),
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness.getRollbackCalls(sessionId), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
}),
),
);
it.live(
"appends checkpoint.revert.failed activity when revert is requested without an active session",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some(
(activity) =>
activity.kind === "checkpoint.revert.failed" &&
typeof activity.payload === "object" &&
activity.payload !== null,
),
);
const failureActivity = thread.activities.find(
(activity) => activity.kind === "checkpoint.revert.failed",
);
assert.equal(failureActivity !== undefined, true);
assert.equal(
String(
(failureActivity?.payload as { readonly detail?: string } | undefined)?.detail,
).includes("No active provider session"),
true,
);
}),
),
);
@@ -1,287 +0,0 @@
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
type TestTurnResponse,
} from "./TestProviderAdapter.integration.ts";
import {
codexTurnApprovalFixture,
codexTurnToolFixture,
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory();
yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n");
return cwd;
}).pipe(Effect.provide(NodeServices.layer));
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness;
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(harness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
});
const collectEventsDuring = <A, E, R>(
stream: Stream.Stream<ProviderRuntimeEvent>,
count: number,
action: Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe(
Effect.forkScoped,
);
yield* action;
return yield* Effect.forEach(
Array.from({ length: count }, () => undefined),
() => Queue.take(queue),
{ discard: false },
);
});
const runTurn = (input: {
readonly provider: ProviderServiceShape;
readonly harness: TestProviderAdapterHarness;
readonly sessionId: ProviderSessionId;
readonly userText: string;
readonly response: TestTurnResponse;
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
input.provider.sendTurn({
sessionId: input.sessionId,
input: input.userText,
attachments: [],
}),
);
});
it.effect("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-typed"),
{
provider: "codex",
cwd: fixture.cwd,
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "hello",
response: { events: codexTurnTextFixture },
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-tools"),
{
provider: "codex",
cwd: fixture.cwd,
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "make a small change",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-multi"),
{
provider: "codex",
cwd: fixture.cwd,
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const firstTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
firstTurnEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
const secondTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
secondTurnEvents.map((event) => event.type),
codexTurnApprovalFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-rollback"),
{
provider: "codex",
cwd: fixture.cwd,
},
);
assert.equal((session.threadId ?? "").length > 0, true);
yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* provider.rollbackConversation({
sessionId: session.sessionId,
numTurns: 1,
});
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
assert.deepEqual(rollbackCalls, [1]);
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
assert.equal(readme, "v3\n");
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
-41
View File
@@ -1,41 +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.ts",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
}
}
-19
View File
@@ -1,19 +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 * as fs from "node:fs";
import * as path from "node:path";
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
const target = path.resolve(import.meta.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,68 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
it("returns empty list for empty diff", () => {
expect(parseTurnDiffFilesFromUnifiedDiff("")).toEqual([]);
});
it("parses per-file additions and deletions", () => {
const diff = [
"diff --git a/a.txt b/a.txt",
"index 1111111..2222222 100644",
"--- a/a.txt",
"+++ b/a.txt",
"@@ -1,2 +1,3 @@",
" one",
"-two",
"+two updated",
"+three",
"diff --git a/src/b.ts b/src/b.ts",
"index 3333333..4444444 100644",
"--- a/src/b.ts",
"+++ b/src/b.ts",
"@@ -3,2 +3,0 @@",
"-old",
"-stale",
"",
].join("\n");
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
{ path: "a.txt", additions: 2, deletions: 1 },
{ path: "src/b.ts", additions: 0, deletions: 2 },
]);
});
it("parses rename-only diffs with zero line changes", () => {
const diff = [
"diff --git a/src/old.ts b/src/new.ts",
"similarity index 100%",
"rename from src/old.ts",
"rename to src/new.ts",
"",
].join("\n");
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
{ path: "src/new.ts", additions: 0, deletions: 0 },
]);
});
it("normalizes CRLF input before parsing", () => {
const diff = [
"diff --git a/a.txt b/a.txt",
"index 1111111..2222222 100644",
"--- a/a.txt",
"+++ b/a.txt",
"@@ -1 +1,2 @@",
"-one",
"+one updated",
"+two",
"",
].join("\r\n");
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
{ path: "a.txt", additions: 2, deletions: 1 },
]);
});
});
-27
View File
@@ -1,27 +0,0 @@
import { parsePatchFiles } from "@pierre/diffs";
export interface TurnDiffFileSummary {
readonly path: string;
readonly additions: number;
readonly deletions: number;
}
export function parseTurnDiffFilesFromUnifiedDiff(
diff: string,
): ReadonlyArray<TurnDiffFileSummary> {
const normalized = diff.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
return [];
}
const parsedPatches = parsePatchFiles(normalized);
const files = parsedPatches.flatMap((patch) =>
patch.files.map((file) => ({
path: file.name,
additions: file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0),
deletions: file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0),
})),
);
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
-43
View File
@@ -1,43 +0,0 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "../git/Errors.ts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
*/
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
"CheckpointUnavailableError",
{
threadId: Schema.String,
turnCount: Schema.Number,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`;
}
}
/**
* CheckpointInvariantError - Inconsistent provider/filesystem/catalog state.
*/
export class CheckpointInvariantError extends Schema.TaggedErrorClass<CheckpointInvariantError>()(
"CheckpointInvariantError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`;
}
}
export type CheckpointStoreError =
| GitCommandError
| CheckpointInvariantError
| CheckpointUnavailableError;
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
@@ -1,186 +0,0 @@
import {
CheckpointRef,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
function makeSnapshot(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: input.worktreePath,
latestTurnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
messages: [],
activities: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
},
],
};
}
describe("CheckpointDiffQueryLive", () => {
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.makeUnsafe("project-1");
const threadId = ThreadId.makeUnsafe("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: ({ checkpointRef }) =>
Effect.sync(() => {
hasCheckpointRefCalls.push(checkpointRef);
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(snapshot),
}),
),
);
const result = await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
diff: "diff patch",
});
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.makeUnsafe("thread-missing");
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(""),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
}),
),
);
await expect(
Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
),
).rejects.toThrow("Thread 'thread-missing' not found.");
});
});
@@ -1,169 +0,0 @@
import {
OrchestrationGetTurnDiffResult,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import {
CheckpointDiffQuery,
type CheckpointDiffQueryShape,
} from "../Services/CheckpointDiffQuery.ts";
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff: "",
};
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
});
}
return emptyDiff;
}
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
if (input.toTurnCount > maxTurnCount) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
});
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
});
}
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
});
}
const toCheckpointRef = thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
});
}
const [fromExists, toExists] = yield* Effect.all(
[
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
if (!fromExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
});
}
if (!toExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
});
}
return turnDiff;
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
) =>
getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
getTurnDiff,
getFullThreadDiff,
} satisfies CheckpointDiffQueryShape;
});
export const CheckpointDiffQueryLive = Layer.effect(CheckpointDiffQuery, make);
@@ -1,282 +0,0 @@
/**
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
*
* Implements hidden Git-ref checkpoint capture/restore directly with
* Effect-native child process execution (`effect/unstable/process`).
*
* This layer owns filesystem/Git interactions only; it does not persist
* checkpoint metadata and does not coordinate provider rollback semantics.
*
* @module CheckpointStoreLive
*/
import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.code === 0));
const resolveCheckpointCommit = (
cwd: string,
checkpointRef: CheckpointRef,
): Effect.Effect<string | null, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
git
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
args: ["rev-parse", "--is-inside-work-tree"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
if (!fromCommitOid && input.fallbackFromToHead === true) {
const headCommit = yield* resolveHeadCommit(input.cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid || !toCommitOid) {
return yield* new GitCommandError({
operation,
command: "git diff",
cwd: input.cwd,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const result = yield* git.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
});
return result.stdout;
});
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
return {
isGitRepository,
captureCheckpoint,
hasCheckpointRef,
restoreCheckpoint,
diffCheckpoints,
deleteCheckpointRefs,
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
@@ -1,49 +0,0 @@
/**
* CheckpointDiffQuery - Query interface for computed checkpoint diffs.
*
* Provides read-only diff operations across checkpoint snapshots used by
* orchestration APIs.
*
* @module CheckpointDiffQuery
*/
import type {
OrchestrationGetFullThreadDiffInput,
OrchestrationGetFullThreadDiffResult,
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { CheckpointServiceError } from "../Errors.ts";
/**
* CheckpointDiffQueryShape - Service API for checkpoint diff queries.
*/
export interface CheckpointDiffQueryShape {
/**
* Read the patch diff for a single turn checkpoint transition.
*
* Verifies checkpoint availability in both projection state and filesystem.
*/
readonly getTurnDiff: (
input: OrchestrationGetTurnDiffInput,
) => Effect.Effect<OrchestrationGetTurnDiffResult, CheckpointServiceError>;
/**
* Read the full patch diff across a thread range of checkpoints.
*
* Delegates to turn diff with `fromTurnCount = 0`.
*/
readonly getFullThreadDiff: (
input: OrchestrationGetFullThreadDiffInput,
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
}
/**
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
*/
export class CheckpointDiffQuery extends ServiceMap.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
@@ -1,100 +0,0 @@
/**
* CheckpointStore - Repository interface for filesystem-backed workspace checkpoints.
*
* Owns hidden Git-ref checkpoint capture/restore and diff computation for a
* workspace thread timeline. It does not store user-facing checkpoint metadata
* and does not coordinate provider conversation rollback.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for checkpoint storage operations.
*
* @module CheckpointStore
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { CheckpointStoreError } from "../Errors.ts";
import { CheckpointRef } from "@t3tools/contracts";
export interface CaptureCheckpointInput {
readonly cwd: string;
readonly checkpointRef: CheckpointRef;
}
export interface RestoreCheckpointInput {
readonly cwd: string;
readonly checkpointRef: CheckpointRef;
readonly fallbackToHead?: boolean;
}
export interface DiffCheckpointsInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
}
export interface DeleteCheckpointRefsInput {
readonly cwd: string;
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
/**
* CheckpointStoreShape - Service API for checkpoint capture/restore and diff access.
*/
export interface CheckpointStoreShape {
/**
* Check whether cwd is inside a Git worktree.
*/
readonly isGitRepository: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;
/**
* Capture a checkpoint commit and store it at the provided checkpoint ref.
*
* Uses an isolated temporary Git index and writes a hidden ref.
*/
readonly captureCheckpoint: (
input: CaptureCheckpointInput,
) => Effect.Effect<void, CheckpointStoreError>;
/**
* Check whether a checkpoint ref exists.
*/
readonly hasCheckpointRef: (
input: Omit<RestoreCheckpointInput, "fallbackToHead">,
) => Effect.Effect<boolean, CheckpointStoreError>;
/**
* Restore workspace/staging state to a checkpoint.
*
* Optionally falls back to current `HEAD` when the checkpoint ref is missing.
*/
readonly restoreCheckpoint: (
input: RestoreCheckpointInput,
) => Effect.Effect<boolean, CheckpointStoreError>;
/**
* Compute patch diff between two checkpoint refs.
*
* Can optionally treat missing "from" ref as `HEAD`.
*/
readonly diffCheckpoints: (
input: DiffCheckpointsInput,
) => Effect.Effect<string, CheckpointStoreError>;
/**
* Delete the provided checkpoint refs.
*
* Best-effort delete: missing refs are tolerated.
*/
readonly deleteCheckpointRefs: (
input: DeleteCheckpointRefsInput,
) => Effect.Effect<void, CheckpointStoreError>;
}
/**
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
*/
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
"t3/checkpointing/Services/CheckpointStore",
) {}
-28
View File
@@ -1,28 +0,0 @@
import { Encoding } from "effect";
import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
return CheckpointRef.makeUnsafe(
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
);
}
export function resolveThreadWorkspaceCwd(input: {
readonly thread: {
readonly projectId: ProjectId;
readonly worktreePath: string | null;
};
readonly projects: ReadonlyArray<{
readonly id: ProjectId;
readonly workspaceRoot: string;
}>;
}): string | undefined {
const worktreeCwd = input.thread.worktreePath ?? undefined;
if (worktreeCwd) {
return worktreeCwd;
}
return input.projects.find((project) => project.id === input.thread.projectId)?.workspaceRoot;
}
@@ -1,361 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { ProviderSessionId } from "@t3tools/contracts";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
},
});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
);
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
});
it("ignores non-error structured codex logs", () => {
const line =
"2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("ignores known benign rollout path errors", () => {
const line =
"\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("keeps unknown structured errors", () => {
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
it("keeps plain stderr messages", () => {
const line = "fatal: permission denied";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("prefers codex id when model differs", () => {
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
});
it("keeps non-aliased models as-is", () => {
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches not-found resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
).toBe(true);
});
it("ignores non-resume errors", () => {
expect(
isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
).toBe(false);
});
it("ignores non-recoverable resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/resume failed: timed out waiting for server"),
),
).toBe(false);
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
kind: event.kind,
...(event.message ? { message: event.message } : {}),
});
});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
provider: "codex",
}),
).rejects.toThrow("cwd missing");
expect(events).toHaveLength(1);
expect(events[0]).toEqual({
method: "session/startFailed",
kind: "error",
message: "cwd missing",
});
} finally {
processCwd.mockRestore();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: asSessionId("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",
resumeCursor: {
threadId: "thread_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",
resumeCursor: {
threadId: "thread_1",
},
});
});
it("supports image-only turns", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: asSessionId("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: asSessionId("sess_1"),
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
});
describe("thread checkpoint control", () => {
it("reads thread turns from thread/read", async () => {
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
},
});
const result = await manager.readThread(asSessionId("sess_1"));
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("reads thread turns from flat thread/read responses", async () => {
const { manager, context, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
const result = await manager.readThread(asSessionId("sess_1"));
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("rolls back turns via thread/rollback and resets session running state", async () => {
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [],
},
});
const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
threadId: "thread_1",
numTurns: 2,
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "ready",
activeTurnId: undefined,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [],
});
});
});
-122
View File
@@ -1,122 +0,0 @@
/**
* ServerConfig and NetService - Runtime configuration services.
*
* Defines process-level server configuration and networking helpers used by
* startup and runtime layers.
*
* @module ServerConfig
*/
import * as Net from "node:net";
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
readonly authToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
}
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {}
// Helpers
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
/**
* NetServiceShape - Networking helper operations used during startup.
*/
export interface NetServiceShape {
/**
* Resolve an available listening port, preferring the provided port first.
*
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
/**
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
"t3/config/NetService",
) {
static readonly layer = Layer.succeed(NetService, {
findAvailablePort: (preferred) =>
Effect.callback<number, NetError>((resume) => {
let fallbackServer: Net.Server | null = null;
const server = Net.createServer();
server.listen(preferred, () => {
server.close(() => resume(Effect.succeed(preferred)));
});
server.on("error", () => {
const fallback = Net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
fallback.close(() => {
resume(
port > 0
? Effect.succeed(port)
: Effect.fail(new NetError({ message: "Could not find an available port." })),
);
});
});
fallback.on("error", (cause) => {
resume(
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
);
});
fallbackServer = fallback;
});
return Effect.sync(() => {
server.close();
fallbackServer?.close();
});
}),
});
}
export const resolveStaticDir = Effect.fn(function* () {
const { join, resolve } = yield* Path.Path;
const { exists } = yield* FileSystem.FileSystem;
const bundledClient = resolve(join(import.meta.dirname, "client"));
const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
Effect.orElseSucceed(() => false),
);
if (bundledStat) {
return bundledClient;
}
const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
Effect.orElseSucceed(() => false),
);
if (monorepoStat) {
return monorepoClient;
}
return undefined;
});
-67
View File
@@ -1,67 +0,0 @@
import { Schema } from "effect";
/**
* GitCommandError - Git command execution failed.
*/
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
}
}
/**
* GitHubCliError - GitHub CLI execution or authentication failed.
*/
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
/**
* TextGenerationError - Commit or PR text generation failed.
*/
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Text generation failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerError - Stacked Git workflow orchestration failed.
*/
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git manager failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
*/
export type GitManagerServiceError =
| GitManagerError
| GitCommandError
| GitHubCliError
| TextGenerationError;
@@ -1,205 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const codexPath = path.join(binDir, "codex");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
codexPath,
[
"#!/bin/sh",
'output_path=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" fi",
" shift",
"done",
"cat >/dev/null",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
return binDir;
});
}
function withFakeCodexEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const binDir = yield* makeFakeCodexBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
} else {
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
} else {
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CODEX_STDERR;
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
}),
);
}
const CodexTextGenerationTestLayer = Layer.provideMerge(
CodexTextGenerationLive,
NodeServices.layer,
);
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject:
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
body: "\n- added migration\n- updated tests\n",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
});
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
}),
),
);
it.effect("generates PR content and trims markdown body", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: " Improve orchestration flow\nwith ignored suffix",
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/codex-effect",
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
});
expect(generated.title).toBe("Improve orchestration flow");
expect(generated.body.startsWith("## Summary")).toBe(true);
expect(generated.body.endsWith("\n\n")).toBe(false);
}),
),
);
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
withFakeCodexEnv(
{
output: JSON.stringify({ subject: "ignored", body: "" }),
exitCode: 1,
stderr: "codex execution failed",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
}
}),
),
);
});
@@ -1,393 +0,0 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { TextGenerationError } from "../Errors.ts";
import {
type CommitMessageGenerationResult,
type PrContentGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
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 normalizeCodexError(
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (error instanceof TextGenerationError) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes("Command not found: codex") ||
lower.includes("spawn codex") ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: "Codex CLI (`codex`) is required but not available on PATH.",
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
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]`;
}
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";
}
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const readStreamAsString = (
operation: string,
stream: Stream.Stream<Uint8Array, unknown>,
): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () {
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.sync(() => {
text += Buffer.from(chunk).toString("utf8");
}),
).pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to collect process output"),
),
);
return text;
});
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const writeTempFile = (
operation: string,
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError> => {
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
return fileSystem.writeFileString(filePath, content).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file at ${filePath}.`,
cause,
}),
),
Effect.as(filePath),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const runCodexJson = <T>({
operation,
cwd,
prompt,
outputSchemaJson,
parse,
}: {
operation: "generateCommitMessage" | "generatePrContent";
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
}): Effect.Effect<T, TextGenerationError> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(outputSchemaJson),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.gen(function* () {
const command = ChildProcess.make(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
stdin: {
stream: Stream.make(new TextEncoder().encode(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
concurrency: "unbounded",
}).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
}),
),
);
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
);
const trimmed = rawOutput.trim();
if (trimmed.length === 0) {
return yield* new TextGenerationError({
operation,
detail: "Codex returned an empty response.",
});
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(trimmed) as unknown,
catch: (cause) =>
new TextGenerationError({
operation,
detail: "Codex returned invalid JSON output.",
cause,
}),
});
return yield* Effect.try({
try: () => parse(parsedJson),
catch: (cause) =>
normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
});
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
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");
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
}) satisfies CommitMessageGenerationResult,
),
);
};
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
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");
return runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
}).pipe(
Effect.map(
(generated) =>
({
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
}) satisfies PrContentGenerationResult,
),
);
};
return {
generateCommitMessage,
generatePrContent,
} satisfies TextGenerationShape;
});
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
File diff suppressed because it is too large. Load diff
-759
View File
@@ -1,759 +0,0 @@
import { Cache, Data, Duration, Effect, Exit, FileSystem, Layer, Path } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
upstreamRef: string;
remoteName: string;
upstreamBranch: string;
}> {}
interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
}
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 [filePath] = fromTab.split("\t");
return filePath?.trim().length ? filePath.trim() : null;
}
const parts = line.trim().split(/\s+/g);
const filePath = parts.at(-1) ?? "";
return filePath.length > 0 ? filePath : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function createGitCommandError(
operation: string,
cwd: string,
args: readonly string[],
detail: string,
cause?: unknown,
): GitCommandError {
return new GitCommandError({
operation,
command: commandLabel(args),
cwd,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
const makeGitCore = Effect.gen(function* () {
const git = yield* GitService;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const executeGit = (
operation: string,
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
git
.execute({
operation,
cwd,
args,
allowNonZeroExit: true,
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
})
.pipe(
Effect.flatMap((result) => {
if (options.allowNonZeroExit || result.code === 0) {
return Effect.succeed(result);
}
const stderr = result.stderr.trim();
if (stderr.length > 0) {
return Effect.fail(createGitCommandError(operation, cwd, args, stderr));
}
if (options.fallbackErrorMessage) {
return Effect.fail(
createGitCommandError(operation, cwd, args, options.fallbackErrorMessage),
);
}
return Effect.fail(
createGitCommandError(
operation,
cwd,
args,
`${commandLabel(args)} failed: code=${result.code ?? "null"}`,
),
);
}),
);
const runGit = (
operation: string,
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<void, GitCommandError> =>
executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);
const runGitStdout = (
operation: string,
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<string, GitCommandError> =>
executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(
Effect.map((result) => result.stdout),
);
const resolveCurrentUpstream = (
cwd: string,
): Effect.Effect<
{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null,
GitCommandError
> =>
Effect.gen(function* () {
const upstreamRef = yield* runGitStdout(
"GitCore.resolveCurrentUpstream",
cwd,
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
return null;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
});
const fetchUpstreamRef = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
return runGit(
"GitCore.fetchUpstreamRef",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
true,
);
};
const fetchUpstreamRefForStatus = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
return executeGit(
"GitCore.fetchUpstreamRefForStatus",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
{
allowNonZeroExit: true,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
},
).pipe(Effect.asVoid);
};
const statusUpstreamRefreshCache = yield* Cache.makeWith({
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>
Effect.gen(function* () {
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
upstreamRef: cacheKey.upstreamRef,
remoteName: cacheKey.remoteName,
upstreamBranch: cacheKey.upstreamBranch,
});
return true as const;
}),
// Keep successful refreshes warm; drop failures immediately so next request can retry.
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
});
const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>
Effect.gen(function* () {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
yield* Cache.get(
statusUpstreamRefreshCache,
new StatusUpstreamRefreshCacheKey({
cwd,
upstreamRef: upstream.upstreamRef,
remoteName: upstream.remoteName,
upstreamBranch: upstream.upstreamBranch,
}),
);
});
const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>
Effect.gen(function* () {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
yield* fetchUpstreamRef(cwd, upstream);
});
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
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;
});
const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
Effect.gen(function* () {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.status", cwd, [
"status",
"--porcelain=2",
"--branch",
]),
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
"diff",
"--cached",
"--numstat",
]),
],
{ concurrency: "unbounded" },
);
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(([filePath, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path: filePath, 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,
};
});
const status: GitCoreShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
})),
);
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
Effect.gen(function* () {
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
"diff",
"--cached",
"--name-status",
]).pipe(Effect.map((stdout) => stdout.trim()));
if (stagedSummary.length === 0) {
return null;
}
const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
return {
stagedSummary,
stagedPatch,
};
});
const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
Effect.gen(function* () {
const args = ["commit", "-m", subject];
const trimmedBody = body.trim();
if (trimmedBody.length > 0) {
args.push("-m", trimmedBody);
}
yield* runGit("GitCore.commit.commit", cwd, args);
const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
"rev-parse",
"HEAD",
]).pipe(Effect.map((stdout) => stdout.trim()));
return { commitSha };
});
const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>
Effect.gen(function* () {
const details = yield* statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
return yield* createGitCommandError(
"GitCore.pushCurrentBranch",
cwd,
["push"],
"Cannot push from detached HEAD.",
);
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
"push",
"-u",
"origin",
branch,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: `origin/${branch}`,
setUpstream: true,
};
}
yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
return {
status: "pushed" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
setUpstream: false,
};
});
const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>
Effect.gen(function* () {
const details = yield* statusDetails(cwd);
const branch = details.branch;
if (!branch) {
return yield* createGitCommandError(
"GitCore.pullCurrentBranch",
cwd,
["pull", "--ff-only"],
"Cannot pull from detached HEAD.",
);
}
if (!details.hasUpstream) {
return yield* createGitCommandError(
"GitCore.pullCurrentBranch",
cwd,
["pull", "--ff-only"],
"Current branch has no upstream configured. Push with upstream first.",
);
}
const beforeSha = yield* runGitStdout(
"GitCore.pullCurrentBranch.beforeSha",
cwd,
["rev-parse", "HEAD"],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = yield* runGitStdout(
"GitCore.pullCurrentBranch.afterSha",
cwd,
["rev-parse", "HEAD"],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const refreshed = yield* statusDetails(cwd);
return {
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
upstreamBranch: refreshed.upstreamRef,
};
});
const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>
Effect.gen(function* () {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
[
runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),
runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),
runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [
"diff",
"--patch",
"--minimal",
range,
]),
],
{ concurrency: "unbounded" },
);
return {
commitSummary,
diffSummary,
diffPatch,
};
});
const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>
runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(
Effect.map((stdout) => stdout.trim()),
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
);
const listBranches: GitCoreShape["listBranches"] = (input) =>
Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const result = yield* executeGit(
"GitCore.listBranches.branchNoColor",
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 };
}
return yield* createGitCommandError(
"GitCore.listBranches",
input.cwd,
["branch", "--no-color"],
stderr || "git branch failed",
);
}
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
input.cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
executeGit(
"GitCore.listBranches.worktreeList",
input.cwd,
["worktree", "list", "--porcelain"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
branchRecencyPromise,
],
{ concurrency: "unbounded" },
);
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);
const exists = yield* fileSystem.stat(candidatePath).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
currentPath = exists ? 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 };
});
const createWorktree: GitCoreShape["createWorktree"] = (input) =>
Effect.gen(function* () {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
const worktreePath =
input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
yield* executeGit(
"GitCore.createWorktree",
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{
fallbackErrorMessage: "git worktree add failed",
},
);
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
});
const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
Effect.gen(function* () {
const args = ["worktree", "remove"];
if (input.force) {
args.push("--force");
}
args.push(input.path);
yield* executeGit("GitCore.removeWorktree", input.cwd, args, {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
}).pipe(
Effect.mapError((error) =>
createGitCommandError(
"GitCore.removeWorktree",
input.cwd,
args,
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
error,
),
),
);
});
const createBranch: GitCoreShape["createBranch"] = (input) =>
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
}).pipe(Effect.asVoid);
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.sync(() => {
void Effect.runPromise(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
});
const initRepo: GitCoreShape["initRepo"] = (input) =>
executeGit("GitCore.initRepo", input.cwd, ["init"], {
timeoutMs: 10_000,
fallbackErrorMessage: "git init failed",
}).pipe(Effect.asVoid);
return {
status,
statusDetails,
prepareCommitContext,
commit,
pushCurrentBranch,
pullCurrentBranch,
readRangeContext,
readConfigValue,
listBranches,
createWorktree,
removeWorktree,
createBranch,
checkoutBranch,
initRepo,
} satisfies GitCoreShape;
});
export const GitCoreLive = Layer.effect(GitCore, makeGitCore);
-178
View File
@@ -1,178 +0,0 @@
import { Effect, Layer } from "effect";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "../Errors.ts";
import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
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 GitHubCliError({
operation,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
return new GitHubCliError({
operation,
detail: `GitHub CLI command failed: ${error.message}`,
cause: error,
});
}
return new GitHubCliError({
operation,
detail: "GitHub CLI command failed.",
cause: error,
});
}
function parseOpenPullRequests(raw: string): ReadonlyArray<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> {
const trimmed = raw.trim();
if (trimmed.length === 0) return [];
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("GitHub CLI returned non-array JSON.");
}
const result: Array<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> = [];
for (const entry of parsed) {
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 ||
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
result.push({
number,
title,
url,
baseRefName,
headRefName,
});
}
return result;
}
const makeGitHubCli = Effect.sync(() => {
const execute: GitHubCliShape["execute"] = (input) =>
Effect.tryPromise({
try: () =>
runProcess("gh", input.args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
}),
catch: (error) => normalizeGitHubCliError("execute", error),
});
const service = {
execute,
listOpenPullRequests: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"list",
"--head",
input.headBranch,
"--state",
"open",
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map((result) => result.stdout),
Effect.flatMap((raw) =>
Effect.try({
try: () => parseOpenPullRequests(raw),
catch: (error: unknown) =>
new GitHubCliError({
operation: "listOpenPullRequests",
detail:
error instanceof Error
? `GitHub CLI returned invalid PR list JSON: ${error.message}`
: "GitHub CLI returned invalid PR list JSON.",
...(error !== undefined ? { cause: error } : {}),
}),
}),
),
),
createPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"create",
"--base",
input.baseBranch,
"--head",
input.headBranch,
"--title",
input.title,
"--body-file",
input.bodyFile,
],
}).pipe(Effect.asVoid),
getDefaultBranch: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
}).pipe(
Effect.map((value) => {
const trimmed = value.stdout.trim();
return trimmed.length > 0 ? trimmed : null;
}),
),
} satisfies GitHubCliShape;
return service;
});
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
@@ -1,660 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import { GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import {
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
failWith?: Error;
}
interface FakeGitTextGeneration {
generateCommitMessage: (input: {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, unknown>;
}
function makeTempDir(
prefix: string,
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
}
function runGit(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
unknown,
GitService
> {
return Effect.gen(function* () {
const gitService = yield* GitService;
return yield* gitService.execute({
operation: "GitManager.test.runGit",
cwd,
args,
allowNonZeroExit,
});
});
}
function initRepo(
cwd: string,
): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* runGit(cwd, ["init", "--initial-branch=main"]);
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
yield* runGit(cwd, ["config", "user.name", "Test User"]);
yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");
yield* runGit(cwd, ["add", "README.md"]);
yield* runGit(cwd, ["commit", "-m", "Initial commit"]);
});
}
function createBareRemote(): Effect.Effect<
string,
unknown,
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
yield* runGit(remoteDir, ["init", "--bare"]);
return remoteDir;
});
}
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: () =>
Effect.succeed({
subject: "Implement stacked git actions",
body: "",
}),
generatePrContent: () =>
Effect.succeed({
title: "Add stacked git actions",
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
}),
...overrides,
};
return {
generateCommitMessage: (input) =>
implementation.generateCommitMessage(input).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: "generateCommitMessage",
detail: "fake text generation failed",
...(cause !== undefined ? { cause } : {}),
}),
),
),
generatePrContent: (input) =>
implementation.generatePrContent(input).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: "generatePrContent",
detail: "fake text generation failed",
...(cause !== undefined ? { cause } : {}),
}),
),
),
};
}
const normalizeGhError = (error: Error): GitHubCliError => {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
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 GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
return new GitHubCliError({
operation: "execute",
detail: error.message,
cause: error,
});
};
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
service: GitHubCliShape;
ghCalls: string[];
} {
const prListQueue = [...(scenario.prListSequence ?? [])];
const ghCalls: string[] = [];
const execute: GitHubCliShape["execute"] = (input) => {
const args = [...input.args];
ghCalls.push(args.join(" "));
if (scenario.failWith) {
return Effect.fail(normalizeGhError(scenario.failWith));
}
if (args[0] === "pr" && args[1] === "list") {
const stdout = (prListQueue.shift() ?? "[]") + "\n";
return Effect.succeed({
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
}
if (args[0] === "pr" && args[1] === "create") {
return Effect.succeed({
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 Effect.succeed({
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
}
if (args[0] === "repo" && args[1] === "view") {
return Effect.succeed({
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
}
return Effect.fail(
new GitHubCliError({
operation: "execute",
detail: `Unexpected gh command: ${args.join(" ")}`,
}),
);
};
return {
service: {
execute,
listOpenPullRequests: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"list",
"--head",
input.headBranch,
"--state",
"open",
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map(
(result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,
),
),
createPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"create",
"--base",
input.baseBranch,
"--head",
input.headBranch,
"--title",
input.title,
"--body-file",
input.bodyFile,
],
}).pipe(Effect.asVoid),
getDefaultBranch: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
}).pipe(
Effect.map((result) => {
const value = result.stdout.trim();
return value.length > 0 ? value : null;
}),
),
},
ghCalls,
};
}
function runStackedAction(
manager: GitManagerShape,
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
commitMessage?: string;
},
) {
return manager.runStackedAction(input);
}
function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(GitServiceLive),
Layer.provideMerge(NodeServices.layer),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
gitCoreLayer,
NodeServices.layer,
);
return makeGitManager.pipe(
Effect.provide(managerLayer),
Effect.map((manager) => ({ manager, ghCalls })),
);
}
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes open PR metadata when branch already has an open PR", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
const { manager } = yield* makeManager({
ghScenario: {
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 status = yield* 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.effect("status is resilient to gh lookup failures and returns openPr null", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("Command not found: gh"),
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.openPr).toBeNull();
}),
);
it.effect("creates a commit when working tree is dirty", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
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(
yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("Implement stacked git actions");
}),
);
it.effect("uses custom commit message when provided", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: () =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
};
}),
},
});
const result = yield* runStackedAction(manager, {
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(
yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("feat: custom summary line");
expect(
yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toContain("- details from user");
}),
);
it.effect("skips commit when there are no uncommitted changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
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.effect("commits and pushes with upstream auto-setup when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("origin/feature/stacked-flow");
}),
);
it.effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 42,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/existing-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
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.effect("creates PR when one does not already exist", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
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 result = yield* runStackedAction(manager, {
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.effect("rejects push/pr actions from detached HEAD", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]);
const { manager } = yield* makeManager();
const errorMessage = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("detached HEAD");
}),
);
it.effect("surfaces missing gh binary errors", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("Command not found: gh"),
},
});
const errorMessage = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
}),
);
it.effect("surfaces gh auth errors with guidance", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("authentication failed"),
},
});
const errorMessage = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("gh auth login");
}),
);
});
-321
View File
@@ -1,321 +0,0 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
interface OpenPrInfo {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
return new GitManagerError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function limitContext(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
subject: string;
body: string;
} {
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): { subject: string; body: string } | 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 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 const makeGitManager = Effect.gen(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const findOpenPr = (cwd: string, branch: string) =>
gitHubCli
.listOpenPullRequests({
cwd,
headBranch: branch,
limit: 1,
})
.pipe(
Effect.map((prs) => {
const [first] = prs;
if (!first) {
return null;
}
return {
number: first.number,
title: first.title,
url: first.url,
baseRefName: first.baseRefName,
headRefName: first.headRefName,
} satisfies OpenPrInfo;
}),
);
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
Effect.gen(function* () {
const configured = yield* 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;
}
}
const defaultFromGh = yield* gitHubCli
.getDefaultBranch({ cwd })
.pipe(Effect.catch(() => Effect.succeed(null)));
if (defaultFromGh) {
return defaultFromGh;
}
return "main";
});
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(cwd);
if (!context) {
return { status: "skipped_no_changes" as const };
}
let generated = parseCustomCommitMessage(commitMessage ?? "");
if (!generated) {
generated = yield* textGeneration
.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
}
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
return {
status: "created" as const,
commitSha,
subject: generated.subject,
};
});
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
return yield* gitManagerError(
"runPrStep",
"Cannot create a pull request from detached HEAD.",
);
}
if (!details.hasUpstream) {
return yield* gitManagerError(
"runPrStep",
"Current branch has not been pushed. Push before creating a PR.",
);
}
const existing = yield* findOpenPr(cwd, branch);
if (existing) {
return {
status: "opened_existing" as const,
url: existing.url,
number: existing.number,
baseBranch: existing.baseRefName,
headBranch: existing.headRefName,
title: existing.title,
};
}
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const generated = yield* textGeneration.generatePrContent({
cwd,
baseBranch,
headBranch: branch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
Effect.mapError((cause) =>
gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
),
);
yield* gitHubCli
.createPullRequest({
cwd,
baseBranch,
headBranch: branch,
title: generated.title,
bodyFile,
})
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
const created = yield* findOpenPr(cwd, branch);
if (!created) {
return {
status: "created" as const,
baseBranch,
headBranch: branch,
title: generated.title,
};
}
return {
status: "created" as const,
url: created.url,
number: created.number,
baseBranch: created.baseRefName,
headBranch: created.headRefName,
title: created.title,
};
});
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
const details = yield* gitCore.statusDetails(input.cwd);
const openPr =
details.branch && details.hasUpstream
? yield* findOpenPr(input.cwd, details.branch).pipe(
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
Effect.catch(() => Effect.succeed(null)),
)
: null;
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr,
};
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
commit,
push,
pr,
};
},
);
return {
status,
runStackedAction,
} satisfies GitManagerShape;
});
export const GitManagerLive = Layer.effect(GitManager, makeGitManager);
@@ -1,59 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(result.failure instanceof GitCommandError);
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
-144
View File
@@ -1,144 +0,0 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
cause instanceof GitCommandError
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* (
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, unknown>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff. Show more