Compare commits

..
Author SHA1 Message Date
Julius Marminge ce1b679cc9 Disable shell by default in process runner
- Keep `spawn` shell usage limited to Windows defaults
- Avoid shell-based command execution on other platforms
2026-04-10 01:06:46 -07:00
Julius Marminge 1fd62443af Merge branch 'main' into codex/fix-github-cli-command-injection-vulnerability 2026-04-10 00:59:11 -07:00
Julius Marminge cc5871a8ba Mitigate Windows GH CLI command injection 2026-04-10 00:58:49 -07:00
Julius Marminge 1a05d8ca1a Document remote server network access setup (#1872) 2026-04-10 07:43:38 +00:00
Julius Marminge cf9f236c80 Add headless t3 serve pairing output (#1871) 2026-04-10 00:12:52 -07:00
Julius Marminge e82b987386 Select desktop backend port by sequential scan (#1870) 2026-04-09 21:51:04 -07:00
Julius Marminge ea9e61b266 Align chat composer and toolbar widths (#1869) 2026-04-10 04:42:52 +00:00
Julius Marminge e32077cee7 Persist client settings and saved environment secrets (#1868) 2026-04-09 20:18:41 -07:00
Noah GregoryandJulius Marminge 5d9eb18312 fix: don't let un-updateable builds check for an update (#1808)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 18:27:24 -07:00
Noah Gregory abb84c09e3 fix: use different bundle ID for dev runner (#1806) 2026-04-09 17:57:50 -07:00
Magnus BuvarpandJulius Marminge 65d797c13e feat(web): add surround selection in composer (#1502)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-10 00:53:06 +00:00
Jacob 7c0849fe2e fix(web): harmonize typography in chat messages and code blocks (#1861) 2026-04-09 17:52:41 -07:00
Yash SinghandJulius Marminge 592c234fd5 fix: make file uri links clickable (#1867)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 17:49:35 -07:00
66d76b5d02 Fix composer footer focus ring overflow (#1865)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-10 00:40:27 +00:00
Julius Marmingeandcodex 528bb2a1fa [codex] Harden WebSocket reconnect recovery (#1864)
Co-authored-by: codex <[email protected]>
2026-04-09 17:23:37 -07:00
869789b4ed Extract ChatComposer to fix composer keystroke re-renders (#1857)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-09 16:37:47 -07:00
Julius Marminge 9bedd7140c Debounce reconnect disconnect logging (#1862) 2026-04-09 15:39:28 -07:00
Julius MarmingeandJulius Marminge 70f5dfcef7 Stabilize keybindings toast stream setup (#1860)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 14:26:28 -07:00
Julius Marminge 9847e9b621 fix build (#1859) 2026-04-09 21:20:05 +00:00
Julius Marminge b547fee77e Scope git toast state by thread ref (#1855) 2026-04-09 19:59:30 +00:00
Julius Marminge 7b3cdc6a8c Clarify environment and workspace picker labels (#1854) 2026-04-09 12:51:17 -07:00
Noxire 386eb18a58 Fix persisted composer image hydration typo (#1831) 2026-04-09 18:20:47 +00:00
7372184d06 fix: map runtime modes to correct permission levels (#1587)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-09 18:10:05 +00:00
Klemencina d9ded65dfe fix(desktop): add Copy Link action for chat links (#1835) 2026-04-09 18:07:53 +00:00
Julius Marmingeandcodex 2aa73985ea Refresh local git status on turn completion (#1821)
Co-authored-by: codex <[email protected]>
2026-04-09 11:02:43 -07:00
Julius Marminge 5b3b31b6e6 Use dev proxy for loopback auth and environment requests (#1853) 2026-04-09 17:53:46 +00:00
b7559c4678 Implement server auth bootstrap and pairing flow (#1768)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-09 10:18:30 -07:00
b96308fc5a Prepare datamodel for multi-environment (#1765)
Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-09 02:05:20 +00:00
Kyle Gottfried 72b7f90c50 Add VSCode Insiders and VSCodium icons (#1847) 2026-04-08 18:50:58 -07:00
legs 1ec346c22e Refactor web stores into atomic slices ready to split ChatView (#1708) 2026-04-08 17:25:49 -07:00
Jacob 28e481eb24 fix(web): distinguish singular/plural in pending action submit label (#1826) 2026-04-07 14:46:24 -07:00
Julius Marminge b1934b925a Add explicit timeouts to CI and release workflows (#1825) 2026-04-07 21:13:24 +00:00
Kyle Gottfried 8244fb80e6 Closes #1795 - Support building and developing in a devcontainer (#1791) 2026-04-07 19:41:08 +00:00
afc3924393 Add Zed support to Open actions via editor command aliases (#1303)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-06 16:46:17 -07:00
Julius Marminge 11d456f6c8 Support multi-select pending user inputs (#1797) 2026-04-06 16:08:46 -07:00
Julius Marminge a221542921 Add project rename support in the sidebar (#1798) 2026-04-06 16:06:36 -07:00
Julius Marminge 226ed997e1 Assign default capabilities to Codex custom models (#1793) 2026-04-06 15:29:11 -07:00
sonderandJulius Marminge c6f57a1064 Rename "Chat" to "Build" in interaction mode toggle (#1769)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-06 17:29:58 +00:00
legs 340dbbb36e fix(web): unwrap windows shell command wrappers (#1719) 2026-04-06 17:19:27 +00:00
Julius Marmingeandcodex 53a552e80d Stream git status updates over WebSocket (#1763)
Co-authored-by: codex <[email protected]>
2026-04-06 09:26:29 -07:00
Julius Marminge cf2c628bc0 Use active worktree path for workspace saves (#1762) 2026-04-05 11:22:24 -07:00
Julius Marminge e0874b651d Raise slow RPC ack warning threshold to 15s (#1760) 2026-04-05 16:53:53 +00:00
Danila Yudin 12347082ef [codex] Fix marketing download fallback links (#1747) 2026-04-04 23:25:43 -07:00
Julius Marmingeandcodex 740d7a3216 Use lazy stream accessors for provider runtime events (#1746)
Co-authored-by: codex <[email protected]>
2026-04-04 23:22:55 -07:00
Danila Yudin cd7980b457 [codex] Canonicalize PR number references (#1749) 2026-04-04 19:56:26 -07:00
f2cd53f232 Add WebSocket disconnect recovery and slow RPC toast UX (#1730)
Co-authored-by: Hwanseo Choi <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-04 17:12:49 -07:00
Julius Marmingeandcodex 04a1ae77e6 Proxy browser OTLP traces through the server (#1739)
Co-authored-by: codex <[email protected]>
2026-04-04 13:01:51 -07:00
Julius Marminge 6de4b47ecb Return replay retry state from orchestration recovery (#1728) 2026-04-03 22:05:33 -07:00
27c2b145f8 feat(cli): allow optional positional cwd argument (#1727)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-03 19:49:10 -07:00
8515f02770 Move worktree bootstrap to the server and persist terminal launch context (#1518)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-03 19:49:01 -07:00
Julius Marmingeandcodex e9ed849b53 Persist server OTLP tracing settings across restarts (#1705)
Co-authored-by: codex <[email protected]>
2026-04-02 20:33:30 -07:00
Julius Marmingeandcodex e8f5b4ad5b [codex] Revert stale send spinner fix (#1704)
Co-authored-by: codex <[email protected]>
2026-04-02 20:19:58 -07:00
Julius Marmingeandcodex 752f96e9ae Add server observability tracing and metrics (#1697)
Co-authored-by: codex <[email protected]>
2026-04-03 02:30:51 +00:00
c1yde3 1b272fd709 feat: support IntelliJ IDEA open-in launch (#1673) 2026-04-02 23:57:09 +00:00
Julius Marminge 9013c07f6d Clean up terminal state when threads are archived (#1702) 2026-04-02 16:26:18 -07:00
Vakhtang Vakhtangishvili 085340588a Fix scroll to bottom button flickering near bottom of the chat (#1692) 2026-04-02 23:04:47 +00:00
Harry 48481aa923 Fix stale send spinner after completed turns (#1700) 2026-04-02 22:59:27 +00:00
Julius Marminge da107f315c Fix websocket closing and reopening connections too eagerly (#1701) 2026-04-02 15:56:53 -07:00
IshanandJulius Marminge d2822a8883 fix: use explicit refspec for push in worktrees with slashed branch names (#1684)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 15:29:30 -07:00
Svilen Petrov ae3ea3980d Clicking logo now navigates to threads (#1617) 2026-04-02 21:45:34 +00:00
915a0548c0 Paginate git branch listing and search results (#1691)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 12:38:19 -07:00
Julius Marminge 5ce5472bc3 Scope git action progress toasts to the originating thread (#1675) 2026-04-02 11:39:27 -07:00
Julius Marminge 9ea443d73a Split PR creation into granular progress stages (#1694) 2026-04-02 11:24:24 -07:00
60f7ae86bb Add copy-to-clipboard action for proposed plan card (#1620)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 00:47:47 -07:00
Julius Marmingeandcodex 867cf4cf09 fix: stabilize messages timeline virtualization (#1664)
Co-authored-by: codex <[email protected]>
2026-04-02 00:10:34 -07:00
Julius MarmingeandCursor Agent ae6f9715c6 Normalize sidebar thread state for faster updates (#1668)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 23:56:40 +00:00
Julius Marminge b92c78f552 Scope git query invalidation by cwd (#1670) 2026-04-01 23:52:28 +00:00
801dfe5b41 [codex] fix git remote parsing, PR resolution, and sidebar PR state (#1619)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 16:13:19 -07:00
Julius Marmingeandcodex 823d69f621 perf(server): bootstrap engine from persisted projections (#1648)
Co-authored-by: codex <[email protected]>
2026-04-01 15:07:15 -07:00
Julius Marmingeandcodex 4963fccb05 perf(server): avoid thread-wide scans for message projection (#1647)
Co-authored-by: codex <[email protected]>
2026-04-01 14:48:39 -07:00
Julius Marmingeandcodex dd89d5ce1a perf(server): add targeted projection queries (#1646)
Co-authored-by: codex <[email protected]>
2026-04-01 14:41:03 -07:00
Julius Marmingeandcodex 9132c37c86 [codex] migrate Effect.fn in apps/server/src/persistence/NodeSqliteClient.ts (#1633)
Co-authored-by: codex <[email protected]>
2026-04-01 16:34:52 +00:00
Julius Marmingeandcodex b9c7ea0581 [codex] migrate Effect.fn in apps/server/src/orchestration/Layers/ProviderCommandReactor.ts (#1629)
Co-authored-by: codex <[email protected]>
2026-04-01 16:26:52 +00:00
Julius Marmingeandcodex 556a195c9d [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderService.ts (#1639)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:38 +00:00
Julius Marmingeandcodex 80b282ece7 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderRegistry.ts (#1638)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:36 +00:00
Julius Marmingeandcodex d15075b32d [codex] migrate Effect.fn in apps/server/src/provider/Layers/EventNdjsonLogger.ts (#1636)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:55 +00:00
Julius Marmingeandcodex 9f6686a13d [codex] migrate Effect.fn in apps/server/src/persistence/Layers/Sqlite.ts (#1631)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:26 +00:00
Julius Marmingeandcodex c6ff7c0d5b [codex] migrate Effect.fn in apps/server/src/provider/makeManagedServerProvider.ts (#1640)
Co-authored-by: codex <[email protected]>
2026-04-01 16:03:08 +00:00
Julius Marmingeandcodex a9e5a84c03 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderAdapterRegistry.ts (#1637)
Co-authored-by: codex <[email protected]>
2026-04-01 08:58:04 -07:00
Julius Marmingeandcodex 67ca528fea [codex] migrate Effect.fn in apps/server/src/provider/Layers/ClaudeProvider.ts (#1634)
Co-authored-by: codex <[email protected]>
2026-04-01 15:57:31 +00:00
Julius Marmingeandcodex 6d9b21c5d0 [codex] migrate Effect.fn in apps/server/src/provider/Layers/CodexProvider.ts (#1635)
Co-authored-by: codex <[email protected]>
2026-04-01 08:56:04 -07:00
Julius Marmingeandcodex ddffdfc095 [codex] migrate Effect.fn in apps/server/src/telemetry/Layers/AnalyticsService.ts (#1642)
Co-authored-by: codex <[email protected]>
2026-04-01 08:53:55 -07:00
Julius Marmingeandcodex a58290ed79 [codex] migrate Effect.fn in apps/server/src/git/Layers/CodexTextGeneration.ts (#1624)
Co-authored-by: codex <[email protected]>
2026-04-01 15:53:25 +00:00
Julius Marmingeandcodex 3488ca3570 [codex] migrate Effect.fn in apps/server/src/persistence/Migrations.ts (#1632)
Co-authored-by: codex <[email protected]>
2026-04-01 08:44:49 -07:00
Julius Marmingeandcodex c542ce3369 [codex] migrate Effect.fn in apps/server/src/git/Layers/ClaudeTextGeneration.ts (#1625)
Co-authored-by: codex <[email protected]>
2026-04-01 15:44:38 +00:00
Julius Marmingeandcodex 15f0be848d [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointStore.ts (#1623)
Co-authored-by: codex <[email protected]>
2026-04-01 08:39:23 -07:00
Julius Marmingeandcodex 1c3fa67374 [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts (#1622)
Co-authored-by: codex <[email protected]>
2026-04-01 08:35:54 -07:00
Lars Nieuwenhuis 0ac59d569d Feat: Added Trae IDE support for opening current working directory (#1656) 2026-04-01 15:19:12 +00:00
d8aa2f85df chore: effect rpc and layer based startup (#929)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-31 23:58:35 -07:00
Utkarsh Patil 64d6938cf4 fix(web): consume plans on new-thread implementation (#1203) 2026-03-31 23:48:39 -07:00
0a88719a3a Improve Linux desktop identity packaged builds (#1201)
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-31 20:07:51 -07:00
shivam 0bc94bc24e fixing the input ui at certain endpoints causing the button to overflow. (#1574) 2026-03-31 18:40:14 -07:00
EDM115andJulius Marminge 19eb9e7227 fix(server): parse git branches correctly when column.ui is enabled (#1529)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-31 18:02:09 -07:00
Julius Marminge aa5521dcfb Map fatal Codex stderr to runtime errors (#1615) 2026-03-31 15:10:16 -07:00
Julius Marminge 2d03847ccd Extract project/workspace related functionality to Effect services (#1524) 2026-03-31 00:08:51 -07:00
Julius Marminge d303ac39cb Replace wait-on with internal desktop resource polling (#1600) 2026-03-30 23:17:33 -07:00
Julius Marminge 48fc85e7fe Bump Effect catalog dependencies (#1594) 2026-03-30 22:08:25 +00:00
0ea639196a Refactor web orchestration sync to incremental events and isolated recovery (#1560)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-30 12:51:49 -07:00
Utkarsh Patil 6f51725732 refactor(web): remove redundant add-project cancel button (#1302) 2026-03-30 10:31:38 -07:00
Julius Marminge 8622b952ca Refactor terminal manager onto Effect runtime (#1525) 2026-03-30 10:19:11 -07:00
Julius Marminge f47c1f1046 Update README.md (#1565) 2026-03-30 05:37:28 +00:00
Julius Marminge 145ddfc408 Document T3 Code install methods (#1564) 2026-03-29 22:33:05 -07:00
Ivor 0bb787b90d Clarify provider setup in README (#1406) 2026-03-29 22:09:23 -07:00
Julius Marminge 59f23d7bfd Show archive action on hover with confirm focus (#1561) 2026-03-29 18:36:53 -07:00
Naufal PutraandJulius Marminge 4a4795e5f0 Scroll active item into view in composer menu (#1557)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:33:47 +00:00
Efroim-PropelandJulius Marminge 5b58f74e9a fix(desktop): default confirm dialog selection to "No" (#1400)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-29 18:20:56 -07:00
Julius Marmingeandcodex 32dca3b76b [codex] debounce thread jump hint pills (#1526)
Co-authored-by: codex <[email protected]>
2026-03-29 18:19:37 -07:00
Abdulelah Hajjar 6358444900 fix(web): Fix duplicate highlight in composer slash command menu (#1445) 2026-03-29 18:14:59 -07:00
Alexander VostresandJulius Marminge 792ad4b5c1 Fix model settings getting stuck (#1538)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:13:16 +00:00
Craig d41781987c fix(web): preserve scroll when collapsing large changed-files trees (#1113) 2026-03-29 17:53:21 -07:00
shivamandEwan fc6507066e fix(windows): hover-effect-fix-in-the-branch-ui (#1559)
Co-authored-by: Ewan <[email protected]>
2026-03-29 17:53:03 -07:00
bf9c828aef Make provider model lists dynamic based on auth context (#1556)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-29 17:51:05 -07:00
shivam 7b676b76de fix: show empty project thread state in sidebar (#1546) 2026-03-29 11:47:51 -07:00
Julius Marminge d5f2333173 Show hidden thread status in sidebar (#1517) 2026-03-29 11:47:17 -07:00
Alexander Vostres 40e7dbdae9 Fix for broken Codex model selection for 'Text Generation Model' (#1543) 2026-03-29 11:27:20 -07:00
Julius Marminge a60daa1c76 Wrap orchestration reactor starts in Effect.fn (#1513) 2026-03-29 05:57:32 +00:00
Julius Marminge bc1024caf0 Inline sqlite error classification (#1515) 2026-03-29 05:55:18 +00:00
Julius Marminge a1c428b6e2 Refactor projection pipeline side effects (#1512) 2026-03-28 22:54:37 -07:00
Julius Marminge 00f3efb95b Make DrainableWorker drain off outstanding count (#1514) 2026-03-28 22:52:39 -07:00
Julius Marminge 7f3387a86c Annotate Git core Effect.fn helpers (#1511) 2026-03-28 22:35:18 -07:00
t3-code[bot] 5462d50177 chore(release): prepare v0.0.15 2026-03-29 04:52:14 +00:00
f82bae1668 Update system overhaul (#1505)
Co-authored-by: Jono Kemball <[email protected]>
Co-authored-by: Ariaj Sarkar <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-03-29 04:23:10 +00:00
Julius Marminge 9e60597174 Truncate oversized git diffs instead of failing (#1499) 2026-03-28 20:50:23 -07:00
Julius Marminge afc807ac3f Add new GitHub users to VOUCHED.td (#1508) 2026-03-29 01:28:52 +00:00
Theo BrowneandJulius Marminge 58ba4f1263 Add keyboard shortcuts for jumping to sidebar threads (#1456)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:23:30 -07:00
maria 5513845fd5 feat(threads): auto-generate first-turn thread titles (#1375) 2026-03-28 17:03:01 -07:00
Julius Marminge 33773ff17e Harden Claude stream exit handling (#1504) 2026-03-28 16:13:52 -07:00
Jono KemballandJulius Marminge 64d21bd6d2 fix: Prevent sidebar project dragging when using macos control+click to open context menu (#873)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 23:09:19 +00:00
shivamandJulius Marminge 5210a833a5 Fix sidebar thread panel weird states. (#1497)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 15:58:37 -07:00
maria 5b1d5c1220 fix(ci): use whitespace-insensitive PR size diff (#1500) 2026-03-28 15:49:53 -07:00
Noah GregoryandJulius Marminge f4617e7b19 feat: add mock update server (#1180)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 15:44:13 -07:00
Julius Marminge c426452239 Tighten settings nav and add Escape back navigation (#1503) 2026-03-28 22:01:37 +00:00
Danila YudinandJulius Marminge 73b2f255a9 fix: add noopener to external chat markdown links (#1315)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 11:59:56 -07:00
FllipandJulius Marminge ce463a5360 fix(web): add project path action to sidebar menu (#1436)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:56:46 +00:00
DanielsandDaniel Schwarz 52fa6a7333 fix(desktop): ensure all windows are destroyed before launching the NSIS installer during update process (#1461)
Co-authored-by: Daniel Schwarz <[email protected]>
2026-03-28 11:51:44 -07:00
Rishi Raj Singh ChauhanandJulius Marminge 04298962be Fix server fallback to direct fd read on /proc/self/fd failure (#1488)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:41:26 +00:00
Ibrahim Elkamali 61f983098b fix(web): allow switching away from Ultrathink without manual prompt editing (#1307) 2026-03-28 11:38:29 -07:00
Ryan GastandJulius Marminge 32c1f98a02 Fix Linux desktop Codex CLI detection at startup (#1100)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:21:56 +00:00
smalitobulesandsmalitobules 5851b8aca4 fix: trust node-pty install scripts on linux (#1451)
Co-authored-by: smalitobules <[email protected]>
2026-03-28 17:53:29 +00:00
Julius Marminge 3e2df5a782 Normalize typed provider runtime ingestion (#1475) 2026-03-28 10:51:01 -07:00
shivamandJulius Marminge f0cdaf94c2 Add thread archiving and settings navigation (#1359)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 10:48:34 -07:00
Maansen 48196e67a7 fix(web): linkify Windows C:/ paths in terminal output (#1483) 2026-03-28 10:37:36 -07:00
Alexander Vostres 80a176fe1f Add eol=lf to .gitattributes for Windows users (#1491) 2026-03-28 10:34:00 -07:00
Alexander Vostres 42ea7cfae1 Detect command not found when checking codex/claude CLI on Windows (#1492) 2026-03-28 17:28:56 +00:00
Alexander Vostres d2e6c82709 Skip a unit test that is using a bash script on Windows (#1490) 2026-03-28 10:26:13 -07:00
Julius Marminge 23b3f0c3d0 Refactor Codex adapter lifecycle helpers (#1478) 2026-03-27 18:43:35 -07:00
Maxwell BrownandJulius Marminge e08cea3a23 Improve drain semantics via STM in DrainableWorker (#1474)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-27 18:05:14 -07:00
Snowy 83eb396c40 fix(threads): Keep active-turn runtime errors from ending sessions (#1261) 2026-03-27 17:38:31 -07:00
Julius Marminge 59a383e1ea Add Effect.fn refactor checklist (#1476) 2026-03-27 17:35:49 -07:00
Harshit Agarwal fb7260792f fix(claude): avoid resetting the Claude model on every turn (#1466) 2026-03-27 12:04:28 -07:00
Julius Marminge d8a485ea7e Support gh pr checkout pull request references (#1457) 2026-03-27 00:08:45 -07:00
Guilherme Vieira 02989fe600 fix(web): improve chat header badge and title flex distribution (#1309) 2026-03-26 21:47:57 -07:00
Nassim Najjar 648f0676bd Add VS Code Insiders and VSCodium to Open In editor picker (#1392) 2026-03-27 04:46:43 +00:00
Julius Marminge add5f34619 Add Claude context window selection support (#1422) 2026-03-26 14:31:35 -07:00
Julius Marminge 9403429a7a Make server settings authoritative for runtime behavior (#1421) 2026-03-25 23:58:58 -07:00
BeckWangthumboon 37cf0c1144 fix(web): add pointer cursor to composer send button (#1415) 2026-03-26 02:02:18 +00:00
Abdulelah Hajjar bf1f3e1c4f fix(web): clear composer border after picker dismissal (#1382) 2026-03-26 02:01:53 +00:00
morganyandmorgan ye 2aa11ae076 fix(desktop): prevent git actions and terminal toggle from overlapping (#1423)
Co-authored-by: morgan ye <[email protected]>
2026-03-25 23:59:12 +00:00
8888f6a0c9 Add copy action to error toast messages (#1416)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-25 13:01:04 -07:00
ff8d87ddee feat(git): Add Claude as a TextGenerationProvider (#1323)
Co-authored-by: keyzou <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-25 12:08:28 -07:00
ifBars 3289a25e57 fix(web): prevent provider model submenu overlap (#1403) 2026-03-25 16:57:09 +00:00
Jakob Stender GulbergandJakob Guldberg Aaes df5bde7e11 docs: properly linked CLAUDE.md to AGENTS.md (#1328)
Co-authored-by: Jakob Guldberg Aaes <[email protected]>
2026-03-25 16:48:07 +00:00
Julius Marmingeandcodex b3bca04caf fix(security): send sensitive config over a bootstrap fd (#1398)
Co-authored-by: codex <[email protected]>
2026-03-25 09:45:13 -07:00
Julius Marminge bf71e0bc5e Pick sidebar fallback thread after delete (#1395) 2026-03-24 23:38:53 -07:00
Julius Marminge a542a3b168 Persist provider-aware model selections (#1371) 2026-03-24 22:40:32 -07:00
Julius Marminge 56d13faa1a Preserve git action progress until HTTP completion (#1388) 2026-03-24 23:38:56 +00:00
t3-code[bot] 2a435aef66 chore(release): prepare v0.0.14 2026-03-24 19:56:02 +00:00
Julius Marminge 28afb14004 Sort sidebar projects and threads by recency (#1372) 2026-03-24 12:40:42 -07:00
Julius Marminge 8f3515572d Surface context window usage in the UI (#1351) 2026-03-24 12:36:51 -07:00
Julius Marminge 529315b4c8 Preserve terminal history across ANSI control sequences (#1367) 2026-03-24 10:34:41 -07:00
Dean ChérifandClaude Opus 4.6 0a503d0cde fix(provider,claude): handle prompt stream interrupt on session stop (#1365)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-24 09:40:19 -07:00
Raphael Lüthy d4a7e1ac0b feat: add word wrapping setting and in-panel button (#1326) 2026-03-24 09:34:22 -07:00
be1abc88fd feat: add terminal toggle button to chat header (#633)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-03-24 09:28:41 +00:00
Julius MarmingeandCursor Agent 384f35084e Stream git hook progress events for stacked git actions (#1214)
Co-authored-by: Cursor Agent <[email protected]>
2026-03-24 02:25:17 -07:00
Julius MarmingeandCursor Agent 1371ce2cce Run draft-thread project scripts from resolved project/worktree cwd (#1178)
Co-authored-by: Cursor Agent <[email protected]>
2026-03-24 01:49:32 -07:00
maria d6408a2949 refactor(settings): simplify settings layout and controls (#1288) 2026-03-24 00:34:11 -07:00
0x1f99d e823f8f14e ci(github): exclude test files from mixed PR size calculation (#1105) 2026-03-23 20:16:13 -07:00
shivamandJulius Marminge 2b08d86696 Add resizable chat sidebar (#1347)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-24 02:26:33 +00:00
shivam e11fb6e778 fix(web): avoid false draft attachment persistence warnings (#1153) 2026-03-23 17:10:23 -07:00
Julius Marminge d415558915 Flatten Git service layer and switch server paths to base dir (#1255) 2026-03-23 17:02:09 -07:00
Roman 843d6d8678 fix: add license field to npm package (#1272) 2026-03-23 23:31:54 +00:00
shivamandJulius Marminge 754cded24a Load PTY adapter at runtime (#1311)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-23 10:40:51 -07:00
Harshit Agarwal 2b6640af1e fix(claude): load Claude SDK filesystem setting sources (#1334) 2026-03-23 10:09:29 -07:00
9e29c9d728 feat: added configurable base directory. (#826)
Co-authored-by: Mohammed Muzammil Anwar <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-20 15:12:52 -07:00
Julius Marminge ef2569196f Prefer Claude user ID for telemetry identity (#1249) 2026-03-20 11:43:39 -07:00
Utkarsh Patil 34cef6202b fix(web): update add-project toggle label in cancel state (#1248) 2026-03-20 18:31:24 +00:00
Ibrahim Elkamali 25c7003226 fix(web): show health banner for selected provider instead of defaulting to Codex (#1223) 2026-03-20 18:28:05 +00:00
Pranav Goel 46e63b3612 fix(ChatView): update scroll button styles to improve user interaction (#1246) 2026-03-20 18:22:04 +00:00
d373389703 feat(web): persist modelOptions, refactor provider specific logic (#1121)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-03-20 11:17:56 -07:00
maria bc12421736 Show project status dots when collapsed in the sidebar (#1097) 2026-03-20 09:54:52 -07:00
0x1f99dandClaude Opus 4.6 8f11ea44a7 fix(web): add pointer cursor to add project button (#1220)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-20 00:00:33 -07:00
t3-code[bot] 56660b04e9 chore(release): prepare v0.0.13 2026-03-20 03:27:19 +00:00
Julius Marminge 2a237c2001 Use secret release app ID in release workflow (#1217) 2026-03-20 03:14:22 +00:00
77716b4ccb feat: add Claude Code adapter (#179)
Co-authored-by: codex <[email protected]>
Co-authored-by: JustYannicc <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-20 02:54:21 +00:00
eggfriedrice fb18b2de16 fix(web): show text input for adding projects on Linux desktop (#1075) 2026-03-19 10:26:06 -07:00
Utkarsh Patil 0de5742b04 fix: consume plans on implementation (#1133) 2026-03-18 13:09:57 -07:00
Utkarsh Patil b500a36a94 fix: implement button overflow (#1193) 2026-03-18 09:46:09 -07:00
MaskandJulius Marminge 1310045629 Give Agents access to Terminal output (#1032)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:56:51 -07:00
Seif Almotaz BellahandJulius Marminge 579a69eb77 feat: add configurable model for git text generation (#1171)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:33:36 -07:00
Guilherme Vieira 9ee8c4f543 fix(web): fix sidebar project drag clipping with variable-height items (#1176) 2026-03-17 15:31:25 -07:00
Julius Marminge 55560f5116 Use GitHub App token when checking out main in release workflow (#1175) 2026-03-17 14:55:27 -07:00
Utkarsh Patil 3710ddb611 fix: fix menu copy (#1063) 2026-03-17 10:57:31 -07:00
0x1f99d 3fce14bbcf fix(web): restore pointer cursors for sidebar actions (#894) 2026-03-17 08:46:06 -07:00
James d430a0624b Add copy workspace path button to thread action menu (#1128) 2026-03-16 22:34:24 -07:00
Daniel StickerandJulius Marminge 765c1dc9e4 fix(desktop): backfill SSH_AUTH_SOCK from login shell on macOS (#972)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-16 09:05:37 -07:00
Utkarsh Patil e6d9a271fc fix(github): fix bug report issue template for screenshots (#1109) 2026-03-15 22:31:36 -07:00
Ivor 4b811dae61 Fixed Typos in Agents.md (#1120) 2026-03-15 16:34:09 +00:00
Etan HeymanandJulius Marminge 6d76865e74 fix: tighten node engine range for node:sqlite compat (#206) (#1096)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-14 19:22:56 -07:00
Sai Shankar 2bb71f41c3 feat(web): add scroll to bottom pill in chat view (#619) 2026-03-14 10:44:55 -07:00
Stefan Wintergerst cc2ab00074 chore: add .idea/ to .gitignore (#1077) 2026-03-14 16:03:35 +00:00
XanacasandClaude Opus 4.6 8b8e8b38e5 fix(web): unify focus ring styles across sidebar and app (#1079)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-14 15:51:37 +00:00
Vitor Buzinaro 46ea594f02 Actions dialog: autofocus script-name field (#912) 2026-03-14 01:05:12 +00:00
0x1f99d 790fda1a97 feat(github): add issue templates for automatic triage (#896) 2026-03-13 11:29:22 -07:00
Julius Marminge 89ffcf42eb Upgrade oxfmt and oxlint tooling versions (#1010) 2026-03-12 23:24:42 -07:00
876bbd715a Extract reusable clipboard hook and standardize media queries (#1006)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-12 21:03:21 -07:00
0x1f99dandJulius Marminge ac0d1f52a0 fix(web): defer diff worker startup until diff opens (#934)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:47:29 -07:00
0x1f99dandJulius Marminge d0ae0adc99 fix(web): add default thread env mode setting (#892)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:18:20 -07:00
Jono Kemball 995a26660e chore: Upgrade marketing app to Astro 6 (#1005) 2026-03-12 20:18:03 -07:00
dpav02andClaude Opus 4.6 dfd62cfb86 fix(desktop): show dialog after "Check for Updates" menu action (#955)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-12 19:43:07 -07:00
ZortosandJulius Marminge 64dc07a8e5 Add compact Codex tool-call icons and details to the chat timeline (#988)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:42:59 -07:00
Jono Kemball ae4ae9973c chore: update @vitejs/plugin-react to 6.0.0 (#1002) 2026-03-12 19:30:47 -07:00
ZortosandJulius Marminge 36473f7de6 feat: replace worktree toggle with discoverable Select dropdown (#1001)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:26:14 -07:00
(CJ) Chukwudi Nwobodo a14debc83e fix: block image uploads during plan mode questions (#621) 2026-03-12 17:24:53 -07:00
(CJ) Chukwudi Nwobodo 71a7473a81 fix: composer @file autocomplete cursor and spacing bugs (#936) 2026-03-12 16:33:37 -07:00
WilgotMandJulius Marminge 5c03fb62c4 Add Antigravity to supported editors in Open menu (macOS, Windows, and Linux) (#841)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 23:28:32 +00:00
Hugo Blom 727c0cfcbf feat: Allow Overriding Timestamp Format in Settings (#855) 2026-03-12 15:58:51 -07:00
Noah GregoryandJulius Marminge dcd2e5c34f fix: don't restart the app on normal exists in dev runner (#986)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:03:55 -07:00
KiyotakaandJulius Marminge 1e276573c2 feat: add fuzzy workspace entry search (#256)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:00:08 -07:00
Julius Marminge db17ff3323 fix syntax errors from bad merge 2026-03-12 12:40:08 -07:00
Qiaochu Hu b496ae8395 fix: add error logging for code highlighting failures (#951) 2026-03-12 12:35:21 -07:00
Qiaochu Huandhobostay 724f54c2c1 fix: clean up timeout in PlanSidebar to prevent memory leaks (#949)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:32:00 -07:00
Qiaochu Huandhobostay b6eba3347d fix: add logging for WebSocket errors (#948)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:31:19 -07:00
Adam NajiandJulius Marminge 74c22628b3 chore: update actions/checkout and actions/github-script (#956)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:29:07 -07:00
0x1f99dandJulius Marminge 224acebb57 fix(web): add pointer cursor to running stop-generation button (#900)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:15:01 -07:00
Alex Schwartz 85c174a6ca fix: Linux icon now shows up (#807) 2026-03-12 12:09:41 -07:00
Julius Marminge 581d242925 remove triggers 2026-03-12 12:01:55 -07:00
Julius Marminge d9d0216e98 fix pr size workflow 2026-03-12 12:01:27 -07:00
Julius Marminge c52ad29b31 Fix mod+N new thread flow and terminal split limits
- ensure `chat.new` creates a fresh draft after a promoted draft thread
- enforce terminal cap per split group (4) while allowing additional terminal groups
- refine sidebar row selected/active styling via shared class-name logic and tests
2026-03-12 11:50:35 -07:00
Julius Marminge fcbf3f3c22 Fix new-thread shortcuts when terminal is focused
- move chat-wide key handling into `_chat` route-level shortcut handler
- extract reusable `useHandleNewThread` hook and `isTerminalFocused` helper
- update browser WS fixture to support `terminalOpen` RPC shape
2026-03-12 11:50:35 -07:00
Donald Silveira ab0002f99d update project removal copy (#981) 2026-03-12 11:48:23 -07:00
Noah GregoryandJulius Marminge f63cda22fa fix: improve business logic in prompt editor and fix cursor bugs in Plan mode (#867)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 11:24:10 -07:00
Noah Gregory b60a34eba4 fix: fix logo aligment regression on macOS (#960) 2026-03-12 11:13:37 -07:00
Jono Kemball ed4be2c849 fix: Fix response duration for agent to no longer always be 1ms (#866) 2026-03-12 11:12:18 -07:00
Noah Gregory 5e23e9c7c7 add Ymit24 to vouched list (#959) 2026-03-12 11:10:58 -07:00
Guilherme VieiraandJulius Marminge c3bfcc36b8 feat: add selective file staging to commit dialog (#872)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:50:49 -07:00
eggfriedrice a33cc8c758 fix: diff panel unclosable after retainSearchParams middleware (#937) 2026-03-12 10:44:16 -07:00
Magnus BuvarpandJulius Marminge a01d712751 fix(web): resolve preferred editor from available editors & introduce useLocalStorage helper (#662)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:42:17 -07:00
0x1f99d 774cff9a74 ci(github): add pull request size labels (#901) 2026-03-12 09:10:07 -07:00
Ymit24andChristian Smith e3d46b687c feat: split out components from ChatView.tsx (#860)
Co-authored-by: Christian Smith <[email protected]>
2026-03-11 19:21:22 -07:00
Theo Browne 8636ea0ec4 Add maria-rcks to the list of contributors 2026-03-11 17:16:51 -07:00
David Balderston ff6a66dcab Use live thread activities for sidebar status pills (#919) 2026-03-11 14:05:17 -07:00
maria 2ac735657e chore(release): align package versions before building artifacts (#933) 2026-03-11 14:03:49 -07:00
github-actions[bot] bbab1fc891 chore(release): prepare v0.0.10 2026-03-11 17:27:36 +00:00
Julius Marminge 82a50da8b1 revert formatting on mockServiceWorker.js 2026-03-10 18:49:04 -07:00
eggfriedrice 7ddcb239c5 feat: persist diff panel state across thread navigation (#875) 2026-03-10 18:42:39 -07:00
0x1f99d 9e4e221970 chore: added eggfriedrice24 to vouched list (#869) 2026-03-10 17:55:36 -07:00
eggfriedrice e8b0126371 fix: checkpoint diffs never resolve (shared PubSub subscription) (#595) 2026-03-10 16:54:47 -07:00
ranvier2d2andClaude Opus 4.6 90d9a2ad1f fix: map gitignore to ini for Shiki syntax highlighting (#848)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-10 16:50:18 -07:00
Julius Marminge 065ef922bd Require bun fmt for completion and clarify Electron history
- Update AGENTS.md task completion requirements to include `bun fmt`
- Add an inline note explaining why Electron uses hash history
2026-03-10 16:21:28 -07:00
7d11533490 Stabilize runtime orchestration and fix flaky CI tests (#488)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 15:54:34 -07:00
Julius Marminge 1031a226f8 Fix cross-repo PR detection and push remote selection (#788) 2026-03-10 15:05:41 -07:00
0x1f99d ddd98876b5 fix: invalidate workspace entry cache after turn completion and revert (#796) 2026-03-10 14:42:39 -07:00
Adam Naji dfd41da2fd Fix Windows keybindings for font size: use Ctrl+ to increase (#786) 2026-03-10 14:41:02 -07:00
Utkarsh Patil b37279ca21 fix: prevent Codex overrides footer overflow with long binary paths (#707) 2026-03-10 11:46:49 -07:00
Julius Marminge 13eeb07f5f prevent squashing some know errors 2026-03-10 10:38:11 -07:00
Jono Kemball 1e9bac7f6e Sync desktop native theme with web theme setting (#800) 2026-03-10 10:23:52 -07:00
0x1f99dandJulius Marminge 1c290767f2 fix: use commit as the default git action without origin (#642)
* fix(web): avoid push and PR defaults without origin

* fmt

* object here too

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 10:16:37 -07:00
0x1f99dandJulius Marminge 9becb3f40a fix(server): skip auth check when Codex CLI uses a custom model provider (#649)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 10:14:58 -07:00
0x1f99d 2c351726ae fix(contracts): align terminal restart input type across IPC, WS, and server (#597) 2026-03-10 09:46:24 -07:00
Weld 9e891d2e97 Display application version in sidebar and settings (#720) 2026-03-10 09:45:39 -07:00
Jono Kemball b8d07eb852 Add downloads page and shared marketing layout (#802) 2026-03-10 09:18:22 -07:00
Jason LasterandJulius Marminge 223c3dc800 chore(ci): add and apply fmt:check script (#779)
* Add  formatting conventions

* Add a fmt lint check

* rely on defaults

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 00:17:18 -07:00
0x1f99dandJulius Marminge afb6e89bfd feat(web): add shift-click multi-select for sidebar threads (#651)
* feat(web): add shift-click multi-select for sidebar threads

Add support for selecting multiple threads in the sidebar via
Cmd/Ctrl+Click (toggle) and Shift+Click (range select), with
bulk context menu actions for Delete and Mark Unread.

- New threadSelectionStore (Zustand) for ephemeral selection state
  with anchor-based range selection and no-op guards
- Platform-aware modifier detection (Cmd on Mac, Ctrl elsewhere)
  matching existing isMacPlatform pattern in terminal-links
- Extracted deleteThread helper from handleThreadContextMenu for
  reuse by bulk delete, with deletedThreadIds set for correct
  fallback navigation during batch operations
- Selected threads share the active thread highlight style
- Escape key clears selection; plain click clears and navigates
- Right-click on selected thread shows bulk menu; right-click on
  unselected thread clears selection and shows single-thread menu
- 22 unit tests covering toggle, range select, clear, remove,
  and edge cases (cross-project fallback, anchor stability)

* fix(web): filter deleted threads from worktree orphan check during bulk delete

When bulk-deleting threads that share a worktree, the stale threads
closure caused getOrphanedWorktreePathForThread to see the other
threads-being-deleted as still alive, suppressing the orphaned
worktree cleanup prompt. Filter out deletedThreadIds (keeping the
current thread) so the check correctly identifies worktrees that
will have no surviving references.

* fix(web): fix shift-click range selection, distinct selection styling, and deselect on click away

* Preserve thread multi-select on safe sidebar control clicks

- avoid clearing selection on mousedown for thread items and marked safe controls
- centralize the selection-safe selector and add logic tests for clear vs preserve behavior
- simplify thread selection store typing by merging state/actions interface

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 00:03:37 -07:00
Julius Marminge 9309edf4f4 rm test 2026-03-09 22:50:45 -07:00
Julius Marminge d28ced8fd7 Move PR checkout flow to dialog and drop /checkout-pr command
- Replace the inline composer PR menu with a dedicated `PullRequestThreadDialog`
- Remove `/checkout-pr` from composer slash-command parsing and tests
- Fix branch selector virtualization sizing for the checkout-PR row
2026-03-09 22:50:45 -07:00
Julius Marminge 076608021c Namespace PR worktree branch names under t3code
- Change local PR worktree branch format from `pr/<number>-<head>` to `t3code/pr-<number>/<head>`
- Update GitManager tests to assert the new branch naming convention
2026-03-09 22:50:45 -07:00
Julius Marminge fb4f9aa58e Use repo initial branch in GitCore PR fetch integration test
- Return `initialBranch` from test repo setup helper
- Replace hardcoded `main` checkout/push/assertions with detected branch name
2026-03-09 22:50:45 -07:00
Julius Marminge de21f4dcd7 Use GitHubCliLive as default test layer
- Wire `it.layer` to `GitHubCliLive` in `GitHubCli.test.ts`
- Remove redundant `Effect.provide(GitHubCliLive)` calls in individual tests
2026-03-09 22:50:45 -07:00
Julius Marminge 442bc9540e Normalize remote URL matching and migrate GitHubCli tests
- Treat remotes that only differ by trailing slash after `.git` as the same remote
- Add a GitCore regression test for trailing-slash remote reuse
- Refactor `GitHubCli` tests to `@effect/vitest` layer-based effect tests with reset cleanup
2026-03-09 22:50:45 -07:00
Julius Marminge f7570712a7 Avoid fork PR head branch collisions when creating worktrees
- create a unique local branch name for cross-repo PR worktrees (`pr/<number>-<head>`)
- fetch/set upstream against that local branch instead of overwriting local `main`
- add regression tests for fork PRs where head branch is `main`
2026-03-09 22:50:45 -07:00
Julius Marminge 2847655a1a Validate GitHub CLI JSON with Effect Schema decoders
- Replace manual JSON parsing with shared schema-based decoding helpers
- Normalize PR and repository payloads after decoding for safer typed outputs
- Improve invalid JSON error mapping with operation-specific GitHubCliError details
2026-03-09 22:50:45 -07:00
Julius Marminge 268016d872 Fix PR thread upstream tracking for fork branches
- Restore/set upstream tracking when preparing local and reused PR worktrees
- Derive fork `owner/repo` from PR URL when GitHub omits `headRepositoryNameWithOwner`
- Expand GitManager tests to cover local mode, URL-derived fork identity, and reused worktree upstream recovery
2026-03-09 22:50:45 -07:00
Julius Marminge ac3f22c274 Inline branch picker filtering and drop PR-only shortcut
- move branch filtering logic into `BranchToolbarBranchSelector`
- remove unused `filterBranchPickerItems` helper and related tests
- keep create-branch option pinned while filtering by query
2026-03-09 22:50:45 -07:00
Julius Marminge b36888e9cc Preserve fork PR upstreams when preparing local and worktree threads
- add GitCore helpers to ensure remotes, fetch remote branches, and set upstreams
- extend GitHub CLI parsing to include cross-repo PR metadata and repo clone URLs
- update GitManager flow and tests to materialize fork heads and keep tracking on fork remotes
2026-03-09 22:50:45 -07:00
Julius Marminge 9bb9023009 Handle branch selection across main and secondary worktrees
- add `resolveBranchSelectionTarget` to unify checkout cwd/worktree decisions
- reuse existing worktrees when available, including switching back to main repo
- update branch selector to use shared logic and add targeted unit tests
2026-03-09 22:50:45 -07:00
Julius Marminge f70cb5de45 Refine branch picker behavior and gate /checkout-pr by thread type
- Add shared branch picker filtering logic and tests, including PR-reference-only results
- Improve branch selector UX/perf with deferred query filtering, conditional virtualization, and status-based current branch resolution
- Only expose and handle `/checkout-pr` for local draft threads in chat and toolbar UI
2026-03-09 22:50:45 -07:00
Julius Marminge 3d3586800e Add pull-request thread setup for local and worktree modes
- Add git APIs to resolve PR refs and prepare PR thread workspaces
- Support fetching PR head refs into local branches and reusing existing worktrees
- Wire new websocket/contracts/web composer flows for PR-based thread creation
- Expand server/web/contracts tests for PR routing and branch/worktree behavior
2026-03-09 22:50:45 -07:00
Julius Marminge 767de271e9 Use Effect UUID generator as randomUUID fallback
- Replace manual UUID byte formatting fallback in `apps/web/src/lib/utils.ts`
- Use `Effect.runSync(Random.nextUUIDv4)` when `crypto.randomUUID` is unavailable
2026-03-09 22:50:23 -07:00
Hiram Chirino 9d2c2cae37 fix(web): polyfill crypto.randomUUID for non-secure HTTP contexts
Replace direct crypto.randomUUID() calls with a randomUUID() helper in
utils.ts that falls back to crypto.getRandomValues() when the browser
is not in a secure context (e.g. plain HTTP on a non-localhost address).

Signed-off-by: Hiram Chirino <[email protected]>
2026-03-09 22:50:23 -07:00
David Balderston dcccca3f7b Fix UI Overflow when Github Action is 'Commit, Create & Push PR'
Fixes: #769

* Updated wording for label from 'Commit, Create & Push PR' to 'Commit, Create & PR' to allow for it to fit within the current UI size constraints.

wording change
2026-03-09 22:27:55 -07:00
Julius Marminge 4ed89e4ba7 Treat retryable Codex errors as runtime warnings
- Map Codex `error` notifications with `willRetry: true` to `runtime.warning`
- Keep active turns/sessions running during reconnect warnings
- Add adapter and ingestion tests for retry-warning behavior
2026-03-09 17:21:03 -07:00
Satyam Bansal 99dbe4ff02 fix(web): disable add project button for empty path 2026-03-09 16:00:38 -07:00
Julius Marminge 2fc0b01c18 fmt 2026-03-09 15:20:07 -07:00
Julius Marminge 3a86b60680 Render collapsed plan preview directly as markdown
- remove deferred collapsed preview state in `ProposedPlanCard`
- always render collapsed preview with `ChatMarkdown` for simpler, consistent display
2026-03-09 15:20:07 -07:00
Julius Marminge eb7c428a2d Defer proposed plan rendering until expand in ChatView
- Keep long plan cards collapsed with lightweight preview text by default
- Render full plan markdown only after explicit expand to reduce thread open slowness
- Add tests for preview/strip helpers and browser coverage for expand behavior
2026-03-09 15:20:07 -07:00
Cursor AgentandJulius Marminge 9fb9467ed1 fix: keep suppressProjectClickAfterDragRef true on drag cancel to prevent unintended toggle
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-09 15:08:10 -07:00
Julius Marminge e42036485f Improve project drag collision detection in sidebar
- Prefer pointer-based hit testing during project reordering
- Fall back to corner-based collision to make drop targeting more reliable
2026-03-09 15:08:10 -07:00
Julius Marminge f9c3aff294 no longer need experimental for tsconfig aliases 2026-03-09 15:08:10 -07:00
Julius Marminge 3503dbc7d5 pin vite 2026-03-09 15:08:10 -07:00
Julius Marminge b5dde6b9d8 Prevent stale click suppression after project drag cancel
- Reset post-drag click suppression when drag is canceled
- Consume only the synthetic click after drag release, then clear suppression
2026-03-09 15:08:10 -07:00
Julius Marminge a6b22ec1c9 Fix project drag clicks and sidebar collapse/scroll behavior
- prevent accidental project toggles after drag operations
- switch project rows to Collapsible for stable expand/collapse animation
- add optional hidden scrollbar mode to ScrollArea and apply it in SidebarContent
2026-03-09 15:08:10 -07:00
Julius Marminge bb49ebf6e5 Add drag-and-drop project reordering in the sidebar
- wire project list to dnd-kit sortable with vertical drag constraints
- prevent accidental expand/collapse clicks during drag gestures
- update store logic/tests and add dnd-kit dependencies
2026-03-09 15:08:10 -07:00
Levi 2f5e626029 Fix project name badge truncation in chat header
Remove the hard max-w-28 (112px) cap and shrink-0 on the project name
badge so it uses available flex space instead of aggressively truncating.
2026-03-09 14:27:29 -07:00
Julius Marminge 82c0a45ea0 Use Debouncer for composer draft persistence writes
- Replace manual timeout/pending-value debounce logic with `@tanstack/react-pacer` `Debouncer`
- Keep `removeItem`/`flush` behavior while simplifying and standardizing persistence timing
2026-03-09 14:02:29 -07:00
Julius Marminge e765051f14 Use React Pacer throttler for domain event snapshot sync
- Replace manual timeout-based domain event batching with `Throttler`
- Keep provider query invalidation batched with trailing 100ms flushes
- Cancel throttler and reset invalidation flag during EventRouter cleanup
2026-03-09 14:02:29 -07:00
Julius Marminge f5e4df5cab Use Debouncer for store state persistence
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
2026-03-09 14:02:29 -07:00
Julius Marminge 1f47cc6f4e Remove ProviderHealth onReady callback from service interface
- Drop the unused `onReady` hook from `ProviderHealthShape`
- Keep startup health status access focused on `getStatuses`
2026-03-09 14:02:29 -07:00
Tim SmartandClaude Opus 4.6 074d3af79c cleanup
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 6593645c80 perf: run provider health checks in background, notify clients on ready
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.

Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 296eb82c31 perf: throttle domain event processing with 100ms batch window
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.

Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 7a377fc5e4 perf: debounce Zustand store persistence and deduplicate legacy cleanup
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.

Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 90e0c2ab15 perf: debounce composer draft localStorage writes
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.

Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.

Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
2026-03-09 14:02:29 -07:00
Cursor AgentandJulius Marminge 7a3d4d1f31 fix: stabilize onToggleRuntimeMode with useCallback to preserve memo
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-09 11:57:27 -07:00
Julius Marminge e354e8697f Prevent compact diff sidebar from breaking chat composer layout
- Add composer footer/action data attributes for targeted width measurement
- Enforce a minimum composer width before allowing inline diff sidebar
2026-03-09 11:57:27 -07:00
Julius Marminge 993b578512 Use form clientWidth for composer compact footer checks
- Measure composer width from the form element in initial and resize paths
- Avoid relying on ResizeObserver contentRect width for compact footer layout decisions
2026-03-09 11:57:27 -07:00
Julius Marmingeandcodex ed518ef19f Fix provider picker after rebase
Co-authored-by: codex <[email protected]>
2026-03-09 11:57:27 -07:00
Julius Marminge 47117a7d85 Inline SidebarInset base classes and remove dead sidebar logic
- Replace `SIDEBAR_INSET_BASE_CLASSNAME` with an inline class string in `sidebar.tsx`
- Delete the now-unused `sidebar.logic.ts` helper and its focused unit test
2026-03-09 11:57:27 -07:00
Julius Marminge f623810903 Adapt composer footer to compact controls on narrow widths
- add shared footer layout breakpoint helper with tests
- switch chat composer footer to compact menu when width is constrained
- preserve plan sidebar toggle behavior while consolidating footer actions
2026-03-09 11:57:27 -07:00
Julius Marminge e9ffd5752b Fix plan composer layout and sidebar flex shrink behavior
- add `min-w-0` to chat/flex containers to prevent composer/sidebar overflow
- move `BranchToolbar` into the chat column so layout stays aligned with plan sidebar
- extract sidebar inset base classes to shared logic and add a regression test for `min-w-0`
2026-03-09 11:57:27 -07:00
638 changed files with 117407 additions and 26620 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
{
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/node:1": {
"version": "24",
"nodeGypDependencies": true
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.12"
}
},
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
"customizations": {
"vscode": {
"extensions": ["oxc.oxc-vscode"]
}
}
}
+302
View File
@@ -0,0 +1,302 @@
# Remote Architecture
This document describes the target architecture for first-class remote environments in T3 Code.
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
## Goals
- Treat remote environments as first-class product primitives, not special cases.
- Support multiple ways to reach the same environment.
- Keep the T3 server as the execution boundary.
- Let desktop, mobile, and web all share the same conceptual model.
- Avoid introducing a local control plane unless product pressure proves it is necessary.
## Non-goals
- Replacing the existing WebSocket server boundary with a custom transport protocol.
- Making SSH the only remote story.
- Syncing provider auth across machines.
- Shipping every access method in the first iteration.
## High-level architecture
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
Remote support should preserve that boundary.
```text
┌──────────────────────────────────────────────┐
│ Client (desktop / mobile / web) │
│ │
│ - known environments │
│ - connection manager │
│ - environment-aware routing │
└───────────────┬──────────────────────────────┘
│
│ resolves one access endpoint
│
┌───────────────▼──────────────────────────────┐
│ Access method │
│ │
│ - direct ws / wss │
│ - tunneled ws / wss │
│ - desktop-managed ssh bootstrap + forward │
└───────────────┬──────────────────────────────┘
│
│ connects to one T3 server
│
┌───────────────▼──────────────────────────────┐
│ Execution environment = one T3 server │
│ │
│ - environment identity │
│ - provider state │
│ - projects / threads / terminals │
│ - git / filesystem / process runtime │
└──────────────────────────────────────────────┘
```
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
## Domain model
### ExecutionEnvironment
An `ExecutionEnvironment` is one running T3 server instance.
It is the unit that owns:
- provider availability and auth state
- model availability
- projects and threads
- terminal processes
- filesystem access
- git operations
- server settings
It is identified by a stable `environmentId`.
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
### KnownEnvironment
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
It is not server-authored. It is local to a device or client profile.
Examples:
- a saved LAN URL
- a saved public `wss://` endpoint
- a desktop-managed SSH host entry
- a saved tunneled environment
A known environment may or may not know the target `environmentId` before first successful connect.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
This is the key abstraction that keeps SSH from taking over the model.
A single environment may have many endpoints:
- `wss://t3.example.com`
- `ws://10.0.0.25:3773`
- a tunneled relay URL
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
The environment stays the same. Only the access path changes.
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
### Workspace / Project
The current `Project` model remains environment-local.
That means:
- a local clone and a remote clone are different projects
- they may share a `RepositoryIdentity`
- threads still bind to one project in one environment
## Access methods
Access methods answer one question:
How does the client speak WebSocket to a T3 server?
They do not answer:
- how the server got started
- who manages the server process
- whether the environment is local or remote
### 1. Direct WebSocket access
Examples:
- `ws://10.0.0.15:3773`
- `wss://t3.example.com`
This is the base model and should be the first-class default.
Benefits:
- works for desktop, mobile, and web
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
### 2. Tunneled WebSocket access
Examples:
- public relay URLs
- private network relay URLs
- local tunnel products such as pipenet
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
This is especially useful when:
- the host is behind NAT
- inbound ports are unavailable
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
The desktop main process can use SSH to:
- reach a machine
- probe it
- launch or reuse a remote T3 server
- establish a local port forward
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
This keeps the renderer transport model consistent with every other access method.
## Launch methods
Launch methods answer a different question:
How does a T3 server come to exist on the target machine?
Launch and access should stay separate in the design.
### 1. Pre-existing server
The simplest launch method is no launch at all.
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
### 2. Desktop-managed remote launch over SSH
This is the main place where Zed is a useful reference.
Useful ideas to borrow from Zed:
- remote probing
- platform detection
- session directories with pid/log metadata
- reconnect-friendly launcher behavior
- desktop-owned connection UX
What should be different in T3:
- no custom stdio/socket proxy protocol between renderer and remote runtime
- no attempt to make the remote runtime look like an editor transport
- keep the final client-to-server connection as WebSocket
The recommended T3 flow is:
1. Desktop connects over SSH.
2. Desktop probes the remote machine and verifies T3 availability.
3. Desktop launches or reuses a remote T3 server.
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
This is useful for:
- exposing a desktop-hosted environment to mobile
- temporary remote access without changing router or firewall settings
This is still a launch concern, not a new environment kind.
## Why access and launch must stay separate
These concerns are easy to conflate, but separating them prevents architectural drift.
Examples:
- A manually hosted T3 server might be reached through direct `wss`.
- The same server might also be reachable through a tunnel.
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
- A local desktop server might be published through a tunnel for mobile.
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
Only the launch and access paths differ.
## Security model
Remote support must assume that some environments will be reachable over untrusted networks.
That means:
- remote-capable environments should require explicit authentication
- tunnel exposure should not rely on obscurity
- client-saved endpoints should carry enough auth metadata to reconnect safely
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
For publicly reachable environments, authenticated access should be treated as required.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
The relevant lessons are:
- remote bootstrap should be explicit
- reconnect should be first-class
- connection UX belongs in the client shell
- runtime ownership should stay clearly on the remote host
The important mismatch is transport shape.
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
T3 should not copy that part.
T3 already has the right runtime boundary:
- one T3 server per environment
- ordinary HTTP/WebSocket between client and environment
So T3 should borrow Zed's launch discipline, not its transport protocol.
## Recommended rollout
1. First-class known environments and access endpoints.
2. Direct `ws` / `wss` remote environments.
3. Authenticated tunnel-backed environments.
4. Desktop-managed SSH launch and forwarding.
5. Multi-environment UI improvements after the base runtime path is proven.
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
+1 -1
View File
@@ -5,7 +5,7 @@
- `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 dev -- --base-dir ~/.t3-2`
- `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.
+2
View File
@@ -0,0 +1,2 @@
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
* text=auto eol=lf
+117
View File
@@ -0,0 +1,117 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
+101
View File
@@ -0,0 +1,101 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
+4
View File
@@ -19,6 +19,7 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -26,3 +27,6 @@ github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
+13 -8
View File
@@ -8,11 +8,12 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Browser Test, Build
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -20,12 +21,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: |
~/.bun/install/cache
@@ -35,7 +36,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -45,6 +46,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
@@ -68,14 +72,15 @@ jobs:
- 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
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -83,7 +88,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
+75
View File
@@ -0,0 +1,75 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
+292
View File
@@ -0,0 +1,292 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Checkout base repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const { execFileSync } = require("node:child_process");
const issueNumber = context.payload.pull_request.number;
const baseSha = context.payload.pull_request.base.sha;
const headSha = context.payload.pull_request.head.sha;
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testExcludePathspecs = [
":(glob,exclude)**/__tests__/**",
":(glob,exclude)**/test/**",
":(glob,exclude)**/tests/**",
":(glob,exclude)apps/server/integration/**",
":(glob,exclude)**/*.test.*",
":(glob,exclude)**/*.spec.*",
":(glob,exclude)**/*.browser.*",
":(glob,exclude)**/*.integration.*",
];
const sumNumstat = (text) =>
text
.split("\n")
.filter(Boolean)
.reduce((total, line) => {
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
const additions =
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
const deletions =
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
return total + additions + deletions;
}, 0);
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
return "size:XS";
}
if (totalChangedLines < 30) {
return "size:S";
}
if (totalChangedLines < 100) {
return "size:M";
}
if (totalChangedLines < 500) {
return "size:L";
}
if (totalChangedLines < 1000) {
return "size:XL";
}
return "size:XXL";
};
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
stdio: "inherit",
});
execFileSync(
"git",
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
{
stdio: "inherit",
},
);
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
encoding: "utf8",
}).trim();
if (resolvedHeadSha !== headSha) {
core.warning(
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
);
}
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
stdio: "inherit",
});
const diffArgs = [
"diff",
"--numstat",
"--ignore-all-space",
"--ignore-blank-lines",
`${baseSha}...${resolvedHeadSha}`,
];
const totalChangedLines = sumNumstat(
execFileSync(
"git",
diffArgs,
{ encoding: "utf8" },
),
);
const nonTestChangedLines = sumNumstat(
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
encoding: "utf8",
}),
);
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
+43 -19
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v7
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = managedLabels.map((label) => label.name);
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
for (const label of managedLabels) {
try {
@@ -138,13 +138,19 @@ jobs:
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
@@ -159,17 +165,35 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+45 -14
View File
@@ -19,6 +19,7 @@ jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
timeout-minutes: 10
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
@@ -27,7 +28,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- id: release_meta
name: Resolve release version
@@ -61,7 +62,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -81,6 +82,7 @@ jobs:
name: Build ${{ matrix.label }}
needs: preflight
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -107,7 +109,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -118,13 +120,16 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -214,7 +219,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -224,9 +229,10 @@ jobs:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -236,7 +242,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -244,6 +250,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -254,19 +263,20 @@ jobs:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
pattern: desktop-*
merge-multiple: true
@@ -301,12 +311,33 @@ jobs:
name: Finalize release
needs: [preflight, release]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: main
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
- id: app_bot
name: Resolve GitHub App bot identity
env:
GH_TOKEN: ${{ steps.app_token.outputs.token }}
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
run: |
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -314,7 +345,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -343,8 +374,8 @@ jobs:
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
+6
View File
@@ -12,7 +12,13 @@ packages/*/dist
build/
.logs/
release/
release-mock/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
squashfs-root/
+5 -2
View File
@@ -1,13 +1,16 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts"
],
"experimentalSortPackageJson": {}
"sortPackageJson": {}
}
+7
View File
@@ -1,20 +1,24 @@
# Plan: Centralize Model Normalization in Contracts
## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
## Scope
- Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer.
## Proposed Changes
1. Add `packages/contracts/src/model.ts` with:
- Canonical model list
- Alias map
@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Keep renderer tests focused on renderer-only behavior.
## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
4. Add tests for handler parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change IPC 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.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
@@ -1,9 +1,11 @@
# Plan: Decompose CodexAppServerManager
## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
1. Extract modules:
- `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts`
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- Session state transitions
## Risks
- Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics.
## Validation
- Existing tests pass.
- Add module-level tests for parsing and transition logic.
## Done Criteria
- Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests.
+7
View File
@@ -1,9 +1,11 @@
# Plan: Split ChatView into Smaller UI/Logic Units
## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration
- Send/interrupt actions
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
- Hard to test and maintain as one component.
## Scope
- Renderer component boundaries and hooks.
- Keep visual behavior unchanged.
## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession`
- `sendTurn`
@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
4. Add focused tests for hook behavior (error handling, session reuse).
## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation
- `bun run test`
- Manual smoke: send, stream, interrupt, model switch.
## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering.
@@ -1,17 +1,21 @@
# Plan: Move Renderer Persisted-State Validation to Zod
## Summary
Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope
- Renderer state hydration/persistence path.
- No backend/protocol changes.
## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
- Unknown thread/project references filtered
## Risks
- Overly strict schemas could drop valid historical data unexpectedly.
## Validation
- Unit tests for migration/hydration.
- Manual reload test with existing localStorage data.
## Done Criteria
- Store hydration logic is schema-driven.
- Migration behavior is tested and documented.
@@ -1,17 +1,21 @@
# Plan: Add Provider Log Stream Lifecycle Management
## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Desktop provider logging behavior.
- App shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
4. Optional: per-session log files under `.logs/providers/`.
## Risks
- Improper close sequencing may lose final log lines.
## Validation
- Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria
- ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add CI Workflow for Core Quality Gates
## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation
- Repository currently has no CI workflow files.
- Quality checks are only local/manual.
## Scope
- `.github/workflows/ci.yml`
- Bun + Turbo setup in CI.
## Proposed Changes
1. Add `ci.yml` with jobs:
- Setup Bun and Node environment
- Install deps
@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
3. Configure caching for Bun/Turbo as appropriate.
## Risks
- Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured.
## Validation
- Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name.
## Done Criteria
- CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation
- Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope
- Root tooling config and package scripts.
- No runtime code changes.
## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks:
- `biome format --write`
@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
4. Keep checks fast to avoid developer friction.
## Risks
- Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup.
## Validation
- Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically.
## Done Criteria
- Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Expand Event/State Transition Test Coverage
## Summary
Add focused tests for renderer event handling and session evolution logic.
## Motivation
- Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior.
## Scope
- `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes
1. Add tests for `evolveSession`:
- `thread/started`
- `turn/started`
@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.
3. Add reducer integration tests for `APPLY_EVENT`.
## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation
- `bun run test`
- Ensure new tests remain deterministic and fast.
## Done Criteria
- High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly.
@@ -1,17 +1,21 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary
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.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)`
- `kill()`
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
5. Add tests for both implementations.
## Risks
- PTY behavior differs by platform; abstraction must not hide required differences.
## Validation
- Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible.
## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable.
+1 -3
View File
@@ -1,5 +1,3 @@
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).
@@ -39,4 +37,4 @@ 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.
Add architecture notes for service boundaries and error model.
+9
View File
@@ -1,12 +1,14 @@
# 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.
@@ -14,12 +16,14 @@ Current status summary:
- 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:
@@ -29,12 +33,14 @@ Current status summary:
- 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`
@@ -43,16 +49,19 @@ Current status summary:
- 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,6 +1,7 @@
# ProviderService Integration Test Plan
Goal:
- Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive`
- `CheckpointServiceLive`
@@ -13,6 +14,7 @@ Goal:
## 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)
@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
- `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
1. `startSession` initializes checkpoint root exactly once
- Arrange:
- start provider session in git repo.
- Assert:
@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:
- checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root.
2) Turn without filesystem change
2. Turn without filesystem change
- Arrange:
- emit normal turn events, no file mutation.
- Assert:
@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3) Turn with filesystem change
3. Turn with filesystem change
- Arrange:
- mutate `README.md` during turn.
- Assert:
@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`.
4) Multi-turn sequencing and checkpoint monotonicity
4. Multi-turn sequencing and checkpoint monotonicity
- Arrange:
- turn 1: no file change
- turn 2: file change
@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:
- latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas.
5) Revert to checkpoint
5. Revert to checkpoint
- Arrange:
- execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`.
@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:
- DB rows for turns >1 are removed.
- later refs are deleted from git.
6) Capture failure surface
6. Capture failure surface
- Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert:
@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:
## 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:
@@ -101,10 +111,13 @@ Add one ws server integration spec:
## 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,6 +1,7 @@
# Server-Authoritative Event-Sourcing Cleanup Plan
Goal:
- Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing
- strict command routing/validation
@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite
## Commit Series
### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types:
- `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema`
@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite
- 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.).
@@ -113,6 +116,7 @@ CheckpointCatalog ------> SQLite
- 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.
@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite
- 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
@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite
- 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.
@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite
- 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.
@@ -165,6 +172,7 @@ CheckpointCatalog ------> SQLite
- 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).
@@ -177,6 +185,7 @@ CheckpointCatalog ------> SQLite
- 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.
@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite
- 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
@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite
- 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)
@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite
- 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.
+2 -1
View File
@@ -1,10 +1,11 @@
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)
- ...
- ...
@@ -24,21 +24,25 @@
- 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.
@@ -46,17 +50,20 @@ Exit criteria:
## 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.
@@ -64,12 +71,14 @@ Exit criteria:
## 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`
@@ -77,6 +86,7 @@ Primary files:
- `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.
@@ -84,27 +94,32 @@ Exit criteria:
## 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`
@@ -113,23 +128,27 @@ Primary files:
- `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.
@@ -140,6 +159,7 @@ Exit criteria:
- 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.
+5 -4
View File
@@ -5,6 +5,7 @@ _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
@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- 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.
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
### Phase 2
@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- 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>
- [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`
@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- 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))
- 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>
@@ -250,7 +251,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
### 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>
- [ ] `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`
+441
View File
@@ -0,0 +1,441 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
@@ -3,60 +3,81 @@
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
### Key modifications
| File | Change |
|------|--------|
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary
- Keep `ProviderRuntimeEvent` as the canonical provider event contract and `ProviderService` as the only cross-provider facade.
- Do not expose raw Codex payloads or Codex event ordering outside `CodexAdapter.ts` and `codexAppServerManager.ts`.
- Do not expand `ProviderKind` in this change. The runtime stays provider-neutral by contract, while the product remains Codex-only in concrete support.
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes
- Refactor `packages/contracts/src/ws.ts` so push messages are derived from a channel-to-schema map instead of `channel: string` plus `data: unknown`.
- Add `sequence: number` to every server push. Ordering becomes explicit and testable.
- Add structured decode diagnostics with stable machine fields: `code`, `reason`, `expected`, `actual`, `path`, optional `jsonOffset`.
- Remove runtime/test dependence on engine-specific pretty strings. Human-readable formatting remains a logging helper only.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 3. Introduce explicit server readiness and a single push pipeline
- Add a `ServerPushBus` service in `apps/server` backed by one ordered queue/pubsub path. All pushes go through it: `server.welcome`, `server.configUpdated`, terminal events, orchestration domain events.
- Add a `ServerReadiness` service with explicit barriers for:
- HTTP listening
- push bus ready
- keybindings runtime ready
- terminal subscriptions ready
- orchestration subscriptions ready
- Strengthen `server.welcome` semantics: it is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer` should never publish directly from ad hoc background streams once the bus exists.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
### 4. Turn background watchers into explicit runtimes
- Extract keybindings watching into a `KeybindingsRuntime` service with `start`, `ready`, `snapshot`, and `changes`.
- Initial config load, startup sync, cache warmup, and watcher attachment complete before `ready` resolves.
- Keep the real `fs.watch` adapter thin. Most behavior tests use a fake watch source and deterministic change stream.
### 4. Turn background watchers into explicit runtimes — DONE
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 5. Replace polling-based orchestration waiting with receipts
- Add server-owned completion receipts for operations that tests currently infer by polling:
- checkpoint capture complete
- checkpoint diff finalized
- turn processing quiesced
- A receipt means append, projection, and required side effects are complete. It must not mean the provider emitted a certain event sequence.
- Update the orchestration harness and checkpoint tests to await receipts/barriers instead of polling snapshots and git refs.
### 5. Replace polling-based orchestration waiting with receipts — DONE
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding
- Refactor `apps/web/src/wsTransport.ts` into an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Decode and validate typed push payloads at the transport boundary, not downstream in `apps/web/src/wsNativeApi.ts`.
- Keep cached latest welcome/config behavior only if it is modeled as explicit state, not as a late-subscriber race workaround.
### 6. Centralize client transport state and decoding — DONE
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 7. Replace ad hoc test helpers with semantic test clients
- Add a shared `WsTestClient` for server/websocket tests:
- connect
- await semantic welcome
- await typed push by channel and optional predicate
- track `sequence`
- match RPC responses by id
- Add one orchestration test harness that waits on receipts/barriers instead of custom `waitForThread`, `waitForGitRef`, and arbitrary retry loops.
- Keep only a narrow set of integration tests for real filesystem/watch/socket behavior. Move behavioral assertions to deterministic unit-style harnesses.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as “Codex has emitted X.” Readiness is owned by the server runtime, not by provider event order.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
+823
View File
@@ -0,0 +1,823 @@
# Server Auth Model Plan
## Purpose
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
Safe default expectations:
- local desktop-managed: auto-pair allowed
- loopback browser access: explicit bootstrap allowed
- non-loopback bind: auth required
- tunnel/public endpoint: auth required, explicit enablement required
### 5. Browser and native clients may use different session credentials
The auth model should support more than one session credential type even if only one ships first.
Examples:
- browser session cookie
- native bearer/device token
This should be represented in the model now, even if browser cookies are the first implementation.
## Target auth domain
### Route classes
Every route or transport entrypoint should be classified as one of:
1. `public`
2. `bootstrap`
3. `authenticated`
#### `public`
Unauthenticated by definition.
Should be extremely small. Examples:
- static shell needed to render the pairing/login UI
- favicon/assets required for the pairing screen
- a minimal server health/version endpoint if needed
#### `bootstrap`
Used only to exchange a bootstrap credential for a session.
Examples:
- Initial bootstrap envelope over file descriptor at startup
- `POST /api/auth/bootstrap`
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
#### `authenticated`
Everything that reveals machine state or mutates it.
Examples:
- WebSocket upgrade
- orchestration snapshot and events
- terminal open/write/close
- project search and file writes
- git routes
- attachments
- project favicon lookup
- server settings
The default stance should be: if it touches the machine, it is authenticated.
## Credential model
### Bootstrap credentials
Initial credential types to model:
- `desktop-bootstrap`
- `one-time-token`
Possible future credential types:
- `device-code`
- `passkey-assertion`
- `external-identity`
#### `desktop-bootstrap`
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
Properties:
- launcher-provided
- short-lived
- one-time or bounded-use
- never shown to the user as a reusable password
#### `one-time-token`
Used for explicit browser/mobile pairing flows.
Properties:
- short TTL
- one-time use
- safe to embed in a pairing URL fragment
- exchanged for a session credential
### Session credentials
Initial credential types to model:
- `browser-session-cookie`
- `bearer-session-token`
#### `browser-session-cookie`
Primary browser credential.
Properties:
- signed
- `HttpOnly`
- bounded lifetime
- revocable by server key rotation or session invalidation
#### `bearer-session-token`
Reserved for native/mobile or non-browser clients.
Properties:
- opaque token, not a bootstrap secret
- long enough lifetime to survive reconnects
- stored in secure client storage when available
## Auth policy model
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
### Policy examples
#### `DesktopManagedLocalPolicy`
Default for desktop-managed local server.
Allowed bootstrap methods:
- `desktop-bootstrap`
Allowed session methods:
- `browser-session-cookie`
Disabled by default:
- `one-time-token`
- `bearer-session-token`
- password login
- public pairing
#### `LoopbackBrowserPolicy`
Used for browser access on localhost without desktop-managed bootstrap.
Allowed bootstrap methods:
- `one-time-token`
Allowed session methods:
- `browser-session-cookie`
#### `RemoteReachablePolicy`
Used when binding non-loopback or using an explicit remote/tunnel workflow.
Allowed bootstrap methods:
- `one-time-token`
- possibly `desktop-bootstrap` when a desktop shell is brokering access
Allowed session methods:
- `browser-session-cookie`
- `bearer-session-token`
#### `UnsafeNoAuthPolicy`
Should exist only as an explicit escape hatch.
Requirements:
- explicit opt-in flag
- loud startup warnings
- never defaulted automatically
## Effect-native service model
### `ServerAuth`
The main auth facade used by HTTP routes and WebSocket upgrade handling.
Responsibilities:
- classify requests
- authenticate requests
- authorize bootstrap attempts
- create sessions from bootstrap credentials
- enforce policy by environment mode
Sketch:
```ts
export interface ServerAuthShape {
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
routeClass: RouteAuthClass,
) => Effect.Effect<AuthContext, AuthError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, AuthError>;
readonly exchangeBootstrapCredential: (
input: BootstrapExchangeInput,
) => Effect.Effect<SessionGrant, AuthError>;
}
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
"t3/ServerAuth",
) {}
```
### `BootstrapCredentialService`
Owns issuance, storage, validation, and consumption of bootstrap credentials.
Responsibilities:
- issue desktop bootstrap grants
- issue one-time pairing tokens
- validate TTL and single-use semantics
- consume bootstrap grants atomically
Sketch:
```ts
export interface BootstrapCredentialServiceShape {
readonly issueDesktopBootstrap: (
input: IssueDesktopBootstrapInput,
) => Effect.Effect<BootstrapCredential>;
readonly issueOneTimeToken: (
input: IssueOneTimeTokenInput,
) => Effect.Effect<BootstrapCredential>;
readonly consume: (
presented: PresentedBootstrapCredential,
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
}
```
### `SessionCredentialService`
Owns creation and validation of authenticated sessions.
Responsibilities:
- mint cookie sessions
- mint bearer sessions
- validate active session credentials
- revoke sessions if needed later
Sketch:
```ts
export interface SessionCredentialServiceShape {
readonly createBrowserSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
readonly createBearerSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
readonly authenticateCookie: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
readonly authenticateBearer: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
}
```
### `ServerAuthPolicy`
Pure policy/config service that decides which credential types are allowed.
Responsibilities:
- map runtime mode and bind/exposure settings to allowed auth methods
- answer whether a route can be public
- answer whether remote exposure requires auth
This should stay mostly pure and cheap to test.
### `ServerSecretStore`
Owns long-lived server signing keys and secrets.
Responsibilities:
- get or create signing key
- rotate signing key
- abstract secure OS-backed storage vs filesystem fallback
Important:
- prefer platform secure storage when available
- support hardened filesystem fallback for headless/server-only environments
### `BrowserSessionCookieCodec`
Focused utility service for cookie encode/decode/signing behavior.
This should not own policy. It should only own the cookie format.
### `AuthRouteGuards`
Thin helper layer used by routes to enforce auth consistently.
Responsibilities:
- require auth for HTTP route handlers
- classify route auth mode
- convert auth failures into `401` / `403`
This prevents every route from re-implementing the same pattern.
Integrates with `HttpRouter.middleware` to enforce auth consistently.
## Suggested layer graph
```text
ServerSecretStore
├─> BootstrapCredentialService
├─> BrowserSessionCookieCodec
└─> SessionCredentialService
ServerAuthPolicy
├─> BootstrapCredentialService
├─> SessionCredentialService
└─> ServerAuth
ServerAuth
└─> AuthRouteGuards
```
Layer naming should follow existing repo style:
- `ServerSecretStoreLive`
- `BootstrapCredentialServiceLive`
- `SessionCredentialServiceLive`
- `ServerAuthPolicyLive`
- `ServerAuthLive`
- `AuthRouteGuardsLive`
## High-level implementation examples
### Example: WebSocket upgrade auth
Current state:
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
Target shape:
```ts
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateWebSocketUpgrade(request);
return yield* httpApp;
}),
);
```
Then the `/ws` route becomes:
```ts
export const websocketRpcRouteLayer = HttpRouter.add(
"GET",
"/ws",
rpcWebSocketHttpEffect.pipe(
websocketUpgradeAuth,
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
### Example: authenticated HTTP route
For routes like attachments or project favicon:
```ts
const authenticatedRoute = (routeClass: RouteAuthClass) =>
HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateHttpRequest(request, routeClass);
return yield* httpApp;
}),
);
```
Then:
```ts
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
serveAttachment.pipe(
authenticatedRoute(RouteAuthClass.Authenticated),
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
### Example: desktop bootstrap exchange
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
That grant is then exchanged for a browser cookie session when the renderer loads.
Sketch:
```ts
const pairDesktopRenderer = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
const credential = yield* bootstrapService.issueDesktopBootstrap({
audience: "desktop-renderer",
ttlMs: 30_000,
});
return credential;
});
```
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
### Example: one-time pairing URL
For browser-driven pairing:
```ts
const createPairingToken = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
return yield* bootstrapService.issueOneTimeToken({
ttlMs: 5 * 60_000,
audience: "browser",
});
});
```
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
```text
Participants:
DesktopMain = Electron main
SecretStore = secure local secret backend
T3Server = local backend child process
Frontend = desktop renderer
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
SecretStore --> DesktopMain : signing key available
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
DesktopMain -> T3Server : send desktop bootstrap envelope
note over T3Server : policy = DesktopManagedLocalPolicy
note over T3Server : allowed pairing = desktop-bootstrap only
Frontend -> DesktopMain : request local bootstrap grant
DesktopMain --> Frontend : short-lived desktop bootstrap grant
Frontend -> T3Server : POST /api/auth/bootstrap
T3Server -> T3Server : validate desktop bootstrap grant
T3Server -> T3Server : create browser session
T3Server --> Frontend : Set-Cookie: session=...
Frontend -> T3Server : GET /ws + authenticated cookie
T3Server -> T3Server : validate cookie session
T3Server --> Frontend : websocket accepted
```
### `npx t3` user
This is the standalone local server flow.
There is no trusted desktop shell here, so pairing should be explicit.
```text
Participants:
UserShell = npx t3 launcher
T3Server = standalone local server
Browser = browser tab
UserShell -> T3Server : start server
T3Server -> T3Server : getOrCreate("server-signing-key")
note over T3Server : policy = LoopbackBrowserPolicy
UserShell -> T3Server : issue one-time pairing token
T3Server --> UserShell : pairing URL or pairing token
UserShell --> Browser : open /pair?token=...
Browser -> T3Server : GET /pair?token=...
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create browser session
T3Server --> Browser : Set-Cookie: session=...
T3Server --> Browser : redirect to app
Browser -> T3Server : GET /ws + authenticated cookie
T3Server --> Browser : websocket accepted
```
### Phone user with tunneled host
This is the explicit remote access flow for a browser on another device.
The tunnel only provides reachability. It must not imply trust.
Recommended UX:
- desktop shows a QR code
- desktop also shows a copyable pairing URL
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
```text
Participants:
DesktopUser = user at the host machine
DesktopMain = desktop app
Tunnel = tunnel provider
T3Server = T3 server
PhoneBrowser = mobile browser
DesktopUser -> DesktopMain : enable remote access via tunnel
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
DesktopMain -> Tunnel : publish local T3 endpoint
Tunnel --> DesktopMain : public https/wss URL
DesktopMain -> T3Server : issue one-time pairing token
T3Server --> DesktopMain : pairing token
DesktopMain -> DesktopUser : show QR code / shareable URL
DesktopUser -> PhoneBrowser : scan QR / open URL
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
Tunnel -> T3Server : forward request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
Tunnel -> T3Server : forward websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Phone user with private network
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
The auth flow should stay the same.
```text
Participants:
DesktopUser = user at the host machine
T3Server = T3 server
PrivateNet = tailscale / private LAN
PhoneBrowser = mobile browser
DesktopUser -> T3Server : enable private-network access
T3Server -> T3Server : switch policy to RemoteReachablePolicy
DesktopUser -> T3Server : issue one-time pairing token
T3Server --> DesktopUser : pairing URL / QR
DesktopUser -> PhoneBrowser : open private-network URL
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
PrivateNet -> T3Server : route request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
RemoteHost --> SSH : launch result JSON
SSH --> DesktopMain : remote server details
DesktopMain -> SSH : establish local port forward
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1. `ServerAuth` service boundary.
2. route classification and route guards.
3. `ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
## What to defer
- passkeys / WebAuthn
- iCloud Keychain / Face ID-specific UX
- multi-user permissions
- collaboration roles
- OAuth / SSO
- polished session management UI
- complex device approval flows
These can all sit on top of the same bootstrap/session/service split.
## Relationship to future remote environments
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
Keep the design focused on:
- one T3 server
- one auth policy
- multiple credential types
- multiple future access methods
That keeps the server auth model stable even as access methods expand later.
## Recommended implementation order
### Phase 1
- Introduce route auth classes.
- Add `ServerAuth` and `AuthRouteGuards`.
- Move existing `authToken` check behind `ServerAuth`.
- Require auth for all privileged HTTP routes as well as WebSocket.
### Phase 2
- Add `ServerSecretStore` service with platform-specific layer implementations.
- `layerOSXKeychain`, `layer
- Add bootstrap/session split.
- Add browser session cookie support.
- Add one-time bootstrap exchange endpoint.
### Phase 3
- Add desktop bootstrap flow on top of the same services.
- Make desktop-managed local environments default to bootstrap-only pairing.
- Surface auth capabilities in shared contracts and renderer bootstrap.
### Phase 4
- Add non-browser bearer session support if mobile/native needs it.
- Add richer policy modes for remote-reachable environments.
## Acceptance criteria
- No privileged HTTP or WebSocket path bypasses auth policy.
- Local desktop-managed flows still avoid a visible login screen.
- Non-loopback or published environments require explicit authenticated pairing by default.
- Bootstrap and session credentials are distinct in code and in behavior.
- Auth logic is centralized in Effect services/layers rather than route-local branching.
+89
View File
@@ -0,0 +1,89 @@
# Replace React Query With AtomRpc + Atom State
## Summary
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
## Phase 3: Replace React Query Domain By Domain
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
2. Keep Zustand orchestration/event application unchanged.
3. Map current effects exactly:
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
- file creation/deletion/restoration touches `project:${cwd}`
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
- `rpc/orchestrationActions.ts`
- `rpc/terminalActions.ts`
- `rpc/gitActions.ts`
- `rpc/projectActions.ts`
- `platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
- `@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
- `desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
+51
View File
@@ -3,13 +3,16 @@
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.
@@ -17,17 +20,22 @@ Work units:
- 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.
@@ -47,17 +55,22 @@ Work units:
- 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.
@@ -65,17 +78,22 @@ Work units:
- 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.
@@ -84,16 +102,21 @@ Work units:
- 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`.
@@ -102,16 +125,21 @@ Work units:
- 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.
@@ -120,16 +148,21 @@ Work units:
- 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`.
@@ -138,16 +171,21 @@ Work units:
- 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`.
@@ -155,16 +193,21 @@ Work units:
- 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.
@@ -172,16 +215,21 @@ Work units:
- 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.
@@ -192,10 +240,13 @@ Work units:
- 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.
+32
View File
@@ -1,6 +1,7 @@
# 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.
@@ -9,6 +10,7 @@ Status legend:
## 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:
@@ -32,6 +34,7 @@ Status legend:
- 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:
@@ -49,6 +52,7 @@ Status legend:
- 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:
@@ -65,6 +69,7 @@ Status legend:
- 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:
@@ -86,6 +91,7 @@ Status legend:
## 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.
@@ -96,6 +102,7 @@ Status legend:
- 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.
@@ -106,6 +113,7 @@ Status legend:
- 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.
@@ -116,6 +124,7 @@ Status legend:
- 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.
@@ -128,6 +137,7 @@ Status legend:
## 7.3 Required Projected Tables (Read Models)
### P1
- Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table.
- SQL contract:
@@ -145,6 +155,7 @@ Status legend:
- 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:
@@ -165,6 +176,7 @@ Status legend:
- Notes: missing table and projector writes.
### P3
- Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table.
- SQL contract:
@@ -183,6 +195,7 @@ Status legend:
- Notes: missing table and message projection writes.
### P4
- Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table.
- SQL contract:
@@ -201,6 +214,7 @@ Status legend:
- Notes: no canonical activity projection persistence.
### P5
- Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table.
- SQL contract:
@@ -219,6 +233,7 @@ Status legend:
- 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:
@@ -237,6 +252,7 @@ Status legend:
- Notes: missing table and projection logic.
### P7
- Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table.
- SQL contract:
@@ -256,6 +272,7 @@ Status legend:
- 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:
@@ -273,6 +290,7 @@ Status legend:
- Notes: missing table and projection logic.
### P9
- Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table.
- SQL contract:
@@ -286,6 +304,7 @@ Status legend:
- 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.
@@ -296,6 +315,7 @@ Status legend:
- 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.
@@ -308,6 +328,7 @@ Status legend:
## 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`.
@@ -318,6 +339,7 @@ Status legend:
- 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.
@@ -328,6 +350,7 @@ Status legend:
- 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`.
@@ -338,6 +361,7 @@ Status legend:
- 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.
@@ -348,6 +372,7 @@ Status legend:
- 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.
@@ -358,6 +383,7 @@ Status legend:
- 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.
@@ -368,6 +394,7 @@ Status legend:
- 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.
@@ -380,22 +407,27 @@ Status legend:
## 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`.
+3 -3
View File
@@ -2,12 +2,12 @@
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `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)
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `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`)
+31 -5
View File
@@ -1,19 +1,43 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## How to use
## Installation
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
```bash
npx t3
```
You can also just install the desktop app. It's cooler.
### Desktop app
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
## Some notes
@@ -21,6 +45,8 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+63 -41
View File
@@ -1,65 +1,87 @@
# Remote Access Setup
# Remote Access
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
## CLI ↔ Env option map
## Recommended Setup
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
Use a trusted private network that meshes your devices together, such as a tailnet.
| 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. |
That gives you:
> TIP: Use the `--help` flag to see all available options and their descriptions.
- a stable address to connect to
- transport security at the network layer
- less exposure than opening the server to the public internet
## Security First
## Enabling Network Access
- 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.
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
## 1) Build + run server for remote access
### Option 1: Desktop App
Remote access should use the built web app (not local Vite redirect mode).
If you are already running the desktop app and want to make it reachable from other devices:
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
4. Use **Create Link** to generate a pairing link you can share with another device.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
Run the server with `t3 serve`.
```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
npx t3 serve --host "$(tailscale ip -4)"
```
Then open on your phone:
`t3 serve` starts the server without opening a browser and prints:
`http://<your-machine-ip>:3773`
- a connection string
- a pairing token
- a pairing URL
- a QR code for the pairing URL
Example:
From there, connect from another device in either of these ways:
`http://192.168.1.42:3773`
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
Notes:
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
- `--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.
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
## 2) Tailnet / Tailscale access
## How Pairing Works
If you use Tailscale, you can bind directly to your Tailnet address.
The remote device does not need a long-lived secret up front.
```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
```
Instead:
Open from any device in your tailnet:
1. `t3 serve` issues a one-time owner pairing token.
2. The remote device exchanges that token with the server.
3. The server creates an authenticated session for that device.
`http://<tailnet-ip>:3773`
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
Typical uses:
- issue additional pairing credentials
- inspect active sessions
- revoke old pairing links or sessions
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.15",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -24,8 +24,7 @@
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2"
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+37 -19
View File
@@ -1,23 +1,39 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
if (!devServerUrl) {
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
}
const devServer = new URL(devServerUrl);
const port = Number.parseInt(devServer.port, 10);
if (!Number.isInteger(port) || port <= 0) {
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
}
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpHost: devServer.hostname,
tcpPort: port,
});
const childEnv = { ...process.env };
@@ -56,10 +72,7 @@ function startApp() {
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
env: childEnv,
stdio: "inherit",
},
);
@@ -76,12 +89,13 @@ function startApp() {
}
});
app.once("exit", () => {
app.once("exit", (code, signal) => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown && !expectedExits.has(app)) {
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
scheduleRestart();
}
});
@@ -148,13 +162,17 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
});
scheduleRestart();
},
);
watchers.push(watcher);
}
+1 -1
View File
@@ -18,7 +18,7 @@ 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 APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
+119
View File
@@ -0,0 +1,119 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
return true;
} catch {
return false;
}
}
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
if (settled) {
return;
}
settled = true;
socket.removeAllListeners();
socket.destroy();
resolveReady(ready);
};
socket.once("connect", () => {
finish(true);
});
socket.once("timeout", () => {
finish(false);
});
socket.once("error", () => {
finish(false);
});
socket.setTimeout(connectTimeoutMs);
});
}
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
}
let tcpReady = false;
for (const host of tcpHosts) {
tcpReady = await tcpPortIsReady({
host,
port: tcpPort,
connectTimeoutMs,
});
if (tcpReady) {
break;
}
}
return {
pendingFiles,
tcpReady,
};
}
export async function waitForResources({
baseDir,
files = [],
intervalMs = 100,
timeoutMs = 120_000,
tcpHost,
tcpPort,
connectTimeoutMs = 500,
}) {
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
throw new TypeError("waitForResources requires a positive integer tcpPort");
}
const startedAt = Date.now();
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
while (true) {
const { pendingFiles, tcpReady } = await resolvePendingResources({
baseDir,
files,
tcpPort,
tcpHosts,
connectTimeoutMs,
});
if (pendingFiles.length === 0 && tcpReady) {
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const pendingResources = [];
if (!tcpReady) {
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
}
for (const filePath of pendingFiles) {
pendingResources.push(`file:${filePath}`);
}
throw new Error(
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
);
}
await Timers.setTimeout(intervalMs);
}
}
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3773);
expect(canListenOnHost).toHaveBeenCalledTimes(1);
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
});
it("increments sequentially until it finds an available port", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3775);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3774, "127.0.0.1"],
[3775, "127.0.0.1"],
]);
});
it("fails when the scan range is exhausted", async () => {
const canListenOnHost = vi.fn(async () => false);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 65534,
maxPort: 65535,
canListenOnHost,
}),
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
expect(canListenOnHost.mock.calls).toEqual([
[65534, "127.0.0.1"],
[65535, "127.0.0.1"],
]);
});
});
+53
View File
@@ -0,0 +1,53 @@
import * as Effect from "effect/Effect";
import { NetService } from "@t3tools/shared/Net";
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
export interface ResolveDesktopBackendPortOptions {
readonly host: string;
readonly startPort?: number;
readonly maxPort?: number;
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
}
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
Effect.service(NetService).pipe(
Effect.flatMap((net) => net.canListenOnHost(port, host)),
Effect.provide(NetService.layer),
Effect.runPromise,
);
const isValidPort = (port: number): boolean =>
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
export async function resolveDesktopBackendPort({
host,
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
maxPort = MAX_TCP_PORT,
canListenOnHost = defaultCanListenOnHost,
}: ResolveDesktopBackendPortOptions): Promise<number> {
if (!isValidPort(startPort)) {
throw new Error(`Invalid desktop backend start port: ${startPort}`);
}
if (!isValidPort(maxPort)) {
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
}
if (maxPort < startPort) {
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
}
// Keep desktop startup predictable across app restarts by probing upward from
// the same preferred port instead of picking a fresh ephemeral port.
for (let port = startPort; port <= maxPort; port += 1) {
if (await canListenOnHost(port, host)) {
return port;
}
}
throw new Error(
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
);
}
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it, vi } from "vitest";
import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness";
describe("waitForHttpReady", () => {
it("returns once the backend reports a successful session endpoint", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status: 503 }))
.mockResolvedValueOnce(new Response(null, { status: 200 }));
await waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 1_000,
intervalMs: 0,
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("retries after a readiness request stalls past the per-request timeout", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockImplementationOnce(
(_input, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener(
"abort",
() => {
reject(new Error("request timed out"));
},
{ once: true },
);
}) as ReturnType<typeof fetch>,
)
.mockResolvedValueOnce(new Response(null, { status: 200 }));
await waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 100,
intervalMs: 0,
requestTimeoutMs: 1,
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("aborts an in-flight readiness wait", async () => {
const controller = new AbortController();
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
() =>
new Promise((_resolve, reject) => {
controller.signal.addEventListener(
"abort",
() => {
reject(new BackendReadinessAbortedError());
},
{ once: true },
);
}) as ReturnType<typeof fetch>,
);
const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 1_000,
intervalMs: 0,
signal: controller.signal,
});
controller.abort();
await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
});
it("recognizes aborted readiness errors", () => {
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
});
});
+103
View File
@@ -0,0 +1,103 @@
export interface WaitForHttpReadyOptions {
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly requestTimeoutMs?: number;
readonly fetchImpl?: typeof fetch;
readonly signal?: AbortSignal;
}
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_INTERVAL_MS = 100;
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
export class BackendReadinessAbortedError extends Error {
constructor() {
super("Backend readiness wait was aborted.");
this.name = "BackendReadinessAbortedError";
}
}
function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
resolve();
}, ms);
const onAbort = () => {
cleanup();
reject(new BackendReadinessAbortedError());
};
const cleanup = () => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
};
if (signal?.aborted) {
cleanup();
reject(new BackendReadinessAbortedError());
return;
}
signal?.addEventListener("abort", onAbort, { once: true });
});
}
export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
return error instanceof BackendReadinessAbortedError;
}
export async function waitForHttpReady(
baseUrl: string,
options?: WaitForHttpReadyOptions,
): Promise<void> {
const fetchImpl = options?.fetchImpl ?? fetch;
const signal = options?.signal;
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const deadline = Date.now() + timeoutMs;
for (;;) {
if (signal?.aborted) {
throw new BackendReadinessAbortedError();
}
const requestController = new AbortController();
const requestTimeout = setTimeout(() => {
requestController.abort();
}, requestTimeoutMs);
const abortRequest = () => {
requestController.abort();
};
signal?.addEventListener("abort", abortRequest, { once: true });
try {
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
redirect: "manual",
signal: requestController.signal,
});
if (response.ok) {
return;
}
} catch (error) {
if (isBackendReadinessAborted(error)) {
throw error;
}
if (signal?.aborted) {
throw new BackendReadinessAbortedError();
}
// Retry until the backend becomes reachable or the deadline expires.
} finally {
clearTimeout(requestTimeout);
signal?.removeEventListener("abort", abortRequest);
}
if (Date.now() >= deadline) {
throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
}
await delay(intervalMs, signal);
}
}
+234
View File
@@ -0,0 +1,234 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
EnvironmentId,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempPath(fileName: string): string {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
tempDirectories.push(directory);
return path.join(directory, fileName);
}
function makeSecretStorage(available: boolean): DesktopSecretStorage {
return {
isEncryptionAvailable: () => available,
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
decryptString: (value) => {
const decoded = value.toString("utf8");
if (!decoded.startsWith("enc:")) {
throw new Error("invalid secret");
}
return decoded.slice("enc:".length);
},
};
}
const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
};
describe("clientPersistence", () => {
it("persists and reloads client settings", () => {
const settingsPath = makeTempPath("client-settings.json");
writeClientSettings(settingsPath, clientSettings);
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
});
it("persists and reloads saved environment metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
});
it("persists encrypted saved environment secrets when encryption is available", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
}),
).toBe(true);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
records: [
{
...savedRegistryRecord,
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
},
],
});
});
it("preserves existing secrets when encryption is unavailable", () => {
const registryPath = makeTempPath("saved-environments.json");
const availableSecretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: availableSecretStorage,
});
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
secretStorage: makeSecretStorage(false),
}),
).toBe(false);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: availableSecretStorage,
}),
).toBe("bearer-token");
});
it("removes saved environment secrets", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
});
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBeNull();
});
it("treats malformed secrets documents as empty", () => {
const registryPath = makeTempPath("saved-environments.json");
fs.writeFileSync(registryPath, "{}\n", "utf8");
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: makeSecretStorage(true),
}),
).toBeNull();
expect(() =>
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
}),
).not.toThrow();
});
it("returns false when writing a secret without metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: makeSecretStorage(true),
}),
).toBe(false);
});
it("preserves encrypted secrets when metadata is rewritten", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
});
});
+216
View File
@@ -0,0 +1,216 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
}
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
readonly encryptedBearerToken?: string;
}
interface SavedEnvironmentRegistryDocument {
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
}
export interface DesktopSecretStorage {
readonly isEncryptionAvailable: () => boolean;
readonly encryptString: (value: string) => Buffer;
readonly decryptString: (value: Buffer) => string;
}
function readJsonFile<T>(filePath: string): T | null {
try {
if (!FS.existsSync(filePath)) {
return null;
}
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
} catch {
return null;
}
}
function writeJsonFile(filePath: string, value: unknown): void {
const directory = Path.dirname(filePath);
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, filePath);
}
function isPersistedSavedEnvironmentStorageRecord(
value: unknown,
): value is PersistedSavedEnvironmentStorageRecord {
return (
Predicate.isObject(value) &&
typeof value.environmentId === "string" &&
typeof value.label === "string" &&
typeof value.httpBaseUrl === "string" &&
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
if (!Predicate.isObject(parsed)) {
return { records: [] };
}
return {
records: Array.isArray(parsed.records)
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
: [],
};
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
}
export function readSavedEnvironmentRegistry(
registryPath: string,
): readonly PersistedSavedEnvironmentRecord[] {
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeSavedEnvironmentRegistry(
registryPath: string,
records: readonly PersistedSavedEnvironmentRecord[],
): void {
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
const encryptedBearerTokenById = new Map(
currentDocument.records.flatMap((record) =>
record.encryptedBearerToken
? [[record.environmentId, record.encryptedBearerToken] as const]
: [],
),
);
writeJsonFile(registryPath, {
records: records.map((record) => {
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
return encryptedBearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
}
: record;
}),
} satisfies SavedEnvironmentRegistryDocument);
}
export function readSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secretStorage: DesktopSecretStorage;
}): string | null {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
const encoded = document.records.find(
(record) => record.environmentId === input.environmentId,
)?.encryptedBearerToken;
if (!encoded) {
return null;
}
if (!input.secretStorage.isEncryptionAvailable()) {
return null;
}
try {
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
} catch {
return null;
}
}
export function writeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secret: string;
readonly secretStorage: DesktopSecretStorage;
}): boolean {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (!input.secretStorage.isEncryptionAvailable()) {
return false;
}
let found = false;
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
found = true;
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
}
export function removeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
}): void {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (
!document.records.some(
(record) =>
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
} satisfies SavedEnvironmentRegistryDocument);
}
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
+64
View File
@@ -0,0 +1,64 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
writeDesktopSettings,
} from "./desktopSettings";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeSettingsPath() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
tempDirectories.push(directory);
return path.join(directory, "desktop-settings.json");
}
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("persists and reloads the configured server exposure mode", () => {
const settingsPath = makeSettingsPath();
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
});
expect(readDesktopSettings(settingsPath)).toEqual({
serverExposureMode: "network-accessible",
});
});
it("preserves the requested network-accessible preference across temporary fallback", () => {
expect(
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
});
});
it("falls back to defaults when the settings file is malformed", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
});
+51
View File
@@ -0,0 +1,51 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
};
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
): DesktopSettings {
return settings.serverExposureMode === requestedMode
? settings
: {
...settings,
serverExposureMode: requestedMode,
};
}
export function readDesktopSettings(settingsPath: string): DesktopSettings {
try {
if (!FS.existsSync(settingsPath)) {
return DEFAULT_DESKTOP_SETTINGS;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
};
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
};
} catch {
return DEFAULT_DESKTOP_SETTINGS;
}
}
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
const directory = Path.dirname(settingsPath);
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, settingsPath);
}
-15
View File
@@ -1,15 +0,0 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+655 -74
View File
File diff suppressed because it is too large. Load diff
+34 -2
View File
@@ -3,19 +3,50 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
@@ -30,6 +61,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
+1 -2
View File
@@ -25,8 +25,7 @@ export function resolveDesktopRuntimeInfo(
};
}
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
+139
View File
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
expect(
resolveLanAdvertisedHost(
{
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
"10.0.0.9",
),
).toBe("10.0.0.9");
});
it("returns the first usable non-internal IPv4 address", () => {
expect(
resolveLanAdvertisedHost(
{
lo0: [
{
address: "127.0.0.1",
family: "IPv4",
internal: true,
netmask: "255.0.0.0",
cidr: "127.0.0.1/8",
mac: "00:00:00:00:00:00",
},
],
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
undefined,
),
).toBe("192.168.1.44");
});
it("returns null when no usable network address is available", () => {
expect(
resolveLanAdvertisedHost(
{
lo0: [
{
address: "127.0.0.1",
family: "IPv4",
internal: true,
netmask: "255.0.0.0",
cidr: "127.0.0.1/8",
mac: "00:00:00:00:00:00",
},
],
},
undefined,
),
).toBeNull();
});
});
describe("resolveDesktopServerExposure", () => {
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
expect(
resolveDesktopServerExposure({
mode: "local-only",
port: 3773,
networkInterfaces: {},
}),
).toEqual({
mode: "local-only",
bindHost: "127.0.0.1",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: null,
advertisedHost: null,
});
});
it("binds to all interfaces in network-accessible mode", () => {
expect(
resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
}),
).toEqual({
mode: "network-accessible",
bindHost: "0.0.0.0",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
});
});
it("stays network-accessible even when no LAN address is currently detectable", () => {
expect(
resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {},
}),
).toEqual({
mode: "network-accessible",
bindHost: "0.0.0.0",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: null,
advertisedHost: null,
});
});
});
+80
View File
@@ -0,0 +1,80 @@
import type { NetworkInterfaceInfo } from "node:os";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
readonly localHttpUrl: string;
readonly localWsUrl: string;
readonly endpointUrl: string | null;
readonly advertisedHost: string | null;
}
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
};
const isUsableLanIpv4Address = (address: string): boolean =>
!address.startsWith("127.") && !address.startsWith("169.254.");
export function resolveLanAdvertisedHost(
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
explicitHost: string | undefined,
): string | null {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
if (normalizedExplicitHost) {
return normalizedExplicitHost;
}
for (const interfaceAddresses of Object.values(networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isUsableLanIpv4Address(address.address)) continue;
return address.address;
}
}
return null;
}
export function resolveDesktopServerExposure(input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
readonly advertisedHostOverride?: string;
}): DesktopServerExposure {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
if (input.mode === "local-only") {
return {
mode: input.mode,
bindHost: DESKTOP_LOOPBACK_HOST,
localHttpUrl,
localWsUrl,
endpointUrl: null,
advertisedHost: null,
};
}
const advertisedHost = resolveLanAdvertisedHost(
input.networkInterfaces,
input.advertisedHostOverride,
);
return {
mode: input.mode,
bindHost: DESKTOP_LAN_BIND_HOST,
localHttpUrl,
localWsUrl,
endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
advertisedHost,
};
}
@@ -0,0 +1,105 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/usr/local/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "win32",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
+36
View File
@@ -0,0 +1,36 @@
import {
readEnvironmentFromLoginShell,
resolveLoginShell,
ShellEnvironmentReader,
} from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
try {
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
+4 -1
View File
@@ -83,7 +83,10 @@ describe("updateMachine", () => {
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(
downloaded,
"backend shutdown timed out",
);
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
+29
View File
@@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("packaged production builds");
});
it("reports packaged local builds without an update feed as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: false,
}),
).toContain("no update feed");
});
it("allows packaged builds with an update feed", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toBeNull();
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
hasUpdateFeedConfig: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "linux",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("AppImage");
});
+4
View File
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
hasUpdateFeedConfig: boolean;
}): string | null {
if (!args.hasUpdateFeedConfig) {
return "Automatic updates are not available because no update feed is configured.";
}
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^5.7.13"
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.4",
"@astrojs/check": "^0.9.7",
"typescript": "catalog:"
}
}
+228
View File
@@ -0,0 +1,228 @@
---
interface Props {
title?: string;
description?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
} = Astro.props;
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content={description} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>{title}</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<slot />
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
}
}
</style>
+30
View File
@@ -0,0 +1,30 @@
const REPO = "pingdotgg/t3code";
export const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
const CACHE_KEY = "t3code-latest-release";
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
export interface Release {
tag_name: string;
html_url: string;
assets: ReleaseAsset[];
}
export async function fetchLatestRelease(): Promise<Release> {
const cached = sessionStorage.getItem(CACHE_KEY);
if (cached) return JSON.parse(cached);
const data = await fetch(API_URL).then((r) => r.json());
if (data?.assets) {
sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
}
return data;
}
+272
View File
@@ -0,0 +1,272 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
<a id="changelog-link" class="changelog-link" href="#" target="_blank" rel="noopener noreferrer" style="display:none">View changelog<span aria-hidden="true"> &#8599;</span></a>
</p>
<div class="platforms" id="platforms">
<!-- macOS -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
</div>
</section>
<!-- Windows -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
</div>
</section>
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</Layout>
<script>
import { fetchLatestRelease, RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
try {
const release = await fetchLatestRelease();
if (versionLabel && release.tag_name) {
versionLabel.textContent = `Latest (${release.tag_name})`;
}
const changelogLink = document.getElementById("changelog-link") as HTMLAnchorElement | null;
if (changelogLink && release.html_url) {
changelogLink.href = release.html_url;
changelogLink.style.display = "";
}
cards.forEach((card) => {
const suffix = card.dataset.asset;
if (!suffix) return;
const match = (release.assets ?? []).find((a) => a.name.endsWith(`-${suffix}`));
if (match) {
card.href = match.browser_download_url;
} else {
card.href = RELEASES_URL;
}
});
} catch {
if (versionLabel) {
versionLabel.textContent = "Could not load release info.";
}
cards.forEach((card) => {
card.href = RELEASES_URL;
});
}
}
init();
</script>
<style>
.main {
padding: 8vh 1.5rem 4rem;
}
/* ── Heading ── */
.heading {
font-weight: 500;
font-size: clamp(1.75rem, 4vw, 2.75rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin-bottom: 0.5rem;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
.subheading {
font-size: 0.9rem;
color: var(--fg-dim);
margin-bottom: 3.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.1s forwards;
display: flex;
align-items: center;
gap: 0.75rem;
}
.changelog-link {
color: var(--fg-muted);
font-size: 0.8rem;
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.changelog-link:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Platforms ── */
.platforms {
width: 100%;
max-width: 720px;
display: flex;
flex-direction: column;
gap: 2.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.2s forwards;
}
.platform-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.platform-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border);
}
.platform-icon {
width: 1.15em;
height: 1.15em;
color: var(--fg-muted);
flex-shrink: 0;
}
.platform-name {
font-weight: 500;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
/* ── Download cards ── */
.download-cards {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.download-card {
display: flex;
flex-direction: column;
gap: 0.2rem;
padding: 0.85rem 1rem;
border-radius: 10px;
border: 1px solid var(--border);
background: rgba(255, 255, 255, 0.02);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.download-card:hover {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.15);
transform: translateY(-1px);
}
.download-card:active {
transform: translateY(0);
}
.card-arch {
font-weight: 600;
font-size: 0.95rem;
}
.card-format {
font-size: 0.8rem;
color: var(--fg-dim);
}
/* ── Releases link ── */
.releases-link {
margin-top: 3rem;
font-size: 0.825rem;
color: var(--fg-dim);
opacity: 0;
animation: fade-in 1s ease-out 0.35s forwards;
}
.releases-link a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.releases-link a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
padding: 5vh 1.25rem 4rem;
}
.platforms {
padding: 0 0.25rem;
}
.download-cards {
grid-template-columns: 1fr;
}
}
</style>
+42 -238
View File
@@ -1,75 +1,30 @@
---
import Layout from "../layouts/Layout.astro";
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<Layout>
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<a href="/download" class="other-platforms">Other platforms</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</Layout>
<script>
const REPO = "pingdotgg/t3code";
const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
@@ -87,10 +42,7 @@
return null;
}
function pickAsset(
assets: Array<{ name: string; browser_download_url: string }>,
platform: Platform,
): string | null {
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
@@ -125,16 +77,8 @@
label.textContent = platform.label;
try {
const cached = sessionStorage.getItem("t3code-latest-release");
const data = cached
? JSON.parse(cached)
: await fetch(API_URL).then((r) => r.json());
if (!cached && data?.assets) {
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
}
const url = pickAsset(data.assets ?? [], platform);
const release = await fetchLatestRelease();
const url = pickAsset(release.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
@@ -149,120 +93,7 @@
</script>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
@@ -291,7 +122,7 @@
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 5vh;
margin-bottom: 1.25rem;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
@@ -325,6 +156,25 @@
display: block;
}
/* ── Other platforms link ── */
.other-platforms {
font-size: 0.825rem;
color: var(--fg-dim);
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.3s forwards;
transition: color 0.3s ease;
text-decoration: underline;
text-decoration-color: rgba(113, 113, 122, 0.4);
text-underline-offset: 3px;
}
.other-platforms:hover {
color: var(--fg-muted);
text-decoration-color: var(--fg-muted);
}
/* ── Screenshot ── */
.screenshot-wrap {
@@ -358,44 +208,6 @@
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
@@ -410,10 +222,6 @@
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
@@ -425,9 +233,5 @@
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
@@ -1,20 +1,20 @@
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,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,7 +24,9 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
@@ -37,16 +39,18 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.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 { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.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";
@@ -65,7 +69,9 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { ServerConfig } from "../src/config.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -75,14 +81,16 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
function initializeGitWorkspace(cwd: string) {
const initializeGitWorkspace = Effect.fn(function* (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");
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
}
});
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -120,7 +128,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
timeoutMs = 40_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
@@ -205,7 +213,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex";
readonly provider?: ProviderKind;
readonly realCodex?: boolean;
}
@@ -213,7 +221,9 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const sleep = (ms: number) => Effect.sleep(ms);
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -230,13 +240,16 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "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 { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -261,7 +274,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -277,41 +290,75 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
CheckpointStoreLive,
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusLive,
RuntimeReceiptBusTest,
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: null }),
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
streamStatus: () => Stream.empty,
}),
),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -345,13 +392,13 @@ export const makeOrchestrationIntegrationHarness = (
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* sleep(10);
yield* Effect.sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -440,9 +487,7 @@ export const makeOrchestrationIntegrationHarness = (
return waitFor(
readMatchingReceipt,
(
receipt,
): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
@@ -470,13 +515,7 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
yield* shutdown;
});
return {
@@ -10,6 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -35,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -72,10 +73,9 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupt
return "completed";
}
function mapRequestType(requestKind: unknown):
| "command_execution_approval"
| "file_change_approval"
| "unknown" {
function mapRequestType(
requestKind: unknown,
): "command_execution_approval" | "file_change_approval" | "unknown" {
if (requestKind === "command") {
return "command_execution_approval";
}
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex";
readonly provider?: ProviderKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: "codex",
provider: ProviderKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: "codex",
provider: ProviderKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -239,323 +239,323 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
}>
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
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({
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
return session;
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
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,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
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,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
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,
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
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,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
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,
createdAt: nowIso(),
return {
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
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 interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
}
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 queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const getStartCount = (): number => sessionCount;
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Command run",
title: "Ran command",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Command run",
title: "Ran command",
detail: "echo integration",
},
},
@@ -5,10 +5,13 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
ModelSelection,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -25,6 +28,7 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -36,7 +40,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex";
type IntegrationProvider = ProviderKind;
function nowIso() {
return new Date().toISOString();
@@ -49,13 +53,11 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
@@ -68,7 +70,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* sleep(10);
yield* Effect.sleep(10);
}
});
}
@@ -89,7 +91,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
);
).pipe(Effect.provide(NodeServices.layer));
}
function withRealCodexHarness<A, E>(
@@ -99,12 +101,14 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
);
).pipe(Effect.provide(NodeServices.layer));
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -112,7 +116,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5-codex",
defaultModelSelection: {
provider,
model: defaultModel,
},
createdAt,
});
@@ -122,7 +129,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
modelSelection: {
provider,
model: defaultModel,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -136,7 +146,7 @@ const startTurn = (input: {
readonly commandId: string;
readonly messageId: string;
readonly text: string;
readonly provider?: IntegrationProvider;
readonly modelSelection?: ModelSelection;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -148,7 +158,11 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.modelSelection !== undefined
? {
modelSelection: input.modelSelection,
}
: {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
@@ -251,7 +265,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5.3-codex",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
createdAt,
});
@@ -261,7 +278,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5.3-codex",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -882,3 +902,435 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: 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-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: 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-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
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.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
@@ -1,5 +1,6 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
@@ -12,6 +13,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -60,6 +62,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
@@ -83,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
@@ -101,7 +105,6 @@ const runTurn = (input: {
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
@@ -113,7 +116,7 @@ const runTurn = (input: {
);
});
it.effect("replays typed runtime fixture events", () =>
it.live("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
@@ -146,7 +149,7 @@ it.effect("replays typed runtime fixture events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("replays file-changing fixture turn events", () =>
it.live("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -185,7 +188,7 @@ it.effect("replays file-changing fixture turn events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("runs multi-turn tool/approval flow", () =>
it.live("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -239,7 +242,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rolls back provider conversation state only", () =>
it.live("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
+9 -8
View File
@@ -1,34 +1,36 @@
{
"name": "t3",
"version": "0.0.9",
"version": "0.0.15",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
"directory": "apps/server"
},
"bin": {
"t3": "./dist/index.mjs"
"t3": "./dist/bin.mjs"
},
"files": [
"dist"
],
"type": "module",
"scripts": {
"dev": "bun run src/index.ts",
"dev": "bun run src/bin.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/index.mjs",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@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"
"open": "^10.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -38,12 +40,11 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
"node": "^22.16 || ^23.11 || >=24.10"
}
}
+5 -4
View File
@@ -6,7 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -237,9 +240,7 @@ const publishCmd = Command.make(
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly stateDir: string;
readonly attachmentsDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const attachmentsRoot = path.resolve(input.attachmentsDir);
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+6 -8
View File
@@ -44,34 +44,32 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
stateDir,
attachmentsDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
fs.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
stateDir,
attachmentsDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
fs.rmSync(attachmentsDir, { recursive: true, force: true });
}
});
});
+5 -6
View File
@@ -12,8 +12,7 @@ import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN =
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i",
@@ -67,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly stateDir: string;
readonly attachmentsDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
stateDir: input.stateDir,
attachmentsDir: input.attachmentsDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly stateDir: string;
readonly attachmentsDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -86,7 +85,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
stateDir: input.stateDir,
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
@@ -0,0 +1,111 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
);
const makeAuthControlPlaneLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
Layer.provideMerge(BootstrapCredentialServiceLive),
Layer.provideMerge(SessionCredentialServiceLive),
Layer.provideMerge(ServerSecretStoreLive),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provide(makeServerConfigLayer(overrides)),
);
it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
it.effect("creates, lists, and revokes client pairing links", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const created = yield* authControlPlane.createPairingLink({
role: "client",
subject: "one-time-token",
label: "CI phone",
});
const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
const revoked = yield* authControlPlane.revokePairingLink(created.id);
const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
expect(created.role).toBe("client");
expect(created.credential.length).toBeGreaterThan(0);
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
expect(revoked).toBe(true);
expect(listedAfterRevoke).toHaveLength(0);
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const sessionCredentials = yield* SessionCredentialService;
const issued = yield* authControlPlane.issueSession({
label: "deploy-bot",
});
const verified = yield* sessionCredentials.verify(issued.token);
const listedBeforeRevoke = yield* authControlPlane.listSessions();
const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
const listedAfterRevoke = yield* authControlPlane.listSessions();
expect(issued.method).toBe("bearer-session-token");
expect(issued.role).toBe("owner");
expect(issued.client.deviceType).toBe("bot");
expect(issued.client.label).toBe("deploy-bot");
expect(verified.sessionId).toBe(issued.sessionId);
expect(verified.role).toBe("owner");
expect(verified.method).toBe("bearer-session-token");
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
expect(revoked).toBe(true);
expect(listedAfterRevoke).toHaveLength(0);
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
it.effect("surfaces lastConnectedAt through the listed session view", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const sessionCredentials = yield* SessionCredentialService;
const issued = yield* authControlPlane.issueSession({
label: "remote-ipad",
});
const beforeConnect = yield* authControlPlane.listSessions();
yield* sessionCredentials.markConnected(issued.sessionId);
const afterConnect = yield* authControlPlane.listSessions();
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
});
@@ -0,0 +1,176 @@
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Effect, Layer } from "effect";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
import {
AuthControlPlane,
AuthControlPlaneError,
AuthControlPlaneShape,
DEFAULT_SESSION_SUBJECT,
IssuedBearerSession,
IssuedPairingLink,
} from "../Services/AuthControlPlane.ts";
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
if (left.role !== right.role) {
return left.role === "owner" ? -1 : 1;
}
if (left.connected !== right.connected) {
return left.connected ? -1 : 1;
}
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
};
const toAuthControlPlaneError =
(message: string) =>
(cause: unknown): AuthControlPlaneError =>
new AuthControlPlaneError({
message,
cause,
});
export const makeAuthControlPlane = Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const sessions = yield* SessionCredentialService;
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
});
return {
id: issued.id,
credential: issued.credential,
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) =>
pairingLinks
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
.map((pairingLink) =>
pairingLink.label
? ({
id: pairingLink.id,
credential: pairingLink.credential,
role: pairingLink.role,
subject: pairingLink.subject,
label: pairingLink.label,
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink)
: ({
id: pairingLink.id,
credential: pairingLink.credential,
role: pairingLink.role,
subject: pairingLink.subject,
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink),
)
.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
),
),
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
);
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
bootstrapCredentials
.revoke(id)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
sessions
.issue({
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
method: "bearer-session-token",
role: input?.role ?? "owner",
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
},
...(input?.ttl ? { ttl: input.ttl } : {}),
})
.pipe(
Effect.flatMap((issued) => {
if (issued.method !== "bearer-session-token") {
return Effect.fail(
new AuthControlPlaneError({
message: "CLI session issuance produced an unexpected session method.",
}),
);
}
return Effect.succeed({
sessionId: issued.sessionId,
token: issued.token,
method: "bearer-session-token" as const,
role: issued.role,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedBearerSession);
}),
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
);
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
sessions.listActive().pipe(
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
);
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
sessions
.revoke(sessionId)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
sessionId,
) =>
sessions
.revokeAllExcept(sessionId)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
return {
createPairingLink,
listPairingLinks,
revokePairingLink,
issueSession,
listSessions,
revokeSession,
revokeOtherSessionsExcept,
} satisfies AuthControlPlaneShape;
});
export const AuthCoreLive = Layer.mergeAll(
BootstrapCredentialServiceLive,
SessionCredentialServiceLive,
);
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
Layer.provideMerge(AuthRuntimeLive),
);
@@ -0,0 +1,151 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
);
const makeBootstrapCredentialLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
BootstrapCredentialServiceLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(makeServerConfigLayer(overrides)),
);
it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
it.effect("issues pairing tokens in a short manual-entry format", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const issued = yield* bootstrapCredentials.issueOneTimeToken();
expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
const first = yield* bootstrapCredentials.consume(issued.credential);
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
expect(first.method).toBe("one-time-token");
expect(first.role).toBe("client");
expect(first.subject).toBe("one-time-token");
expect(first.label).toBe("Julius iPhone");
expect(issued.label).toBe("Julius iPhone");
expect(second._tag).toBe("BootstrapCredentialError");
expect(second.message).toContain("Unknown bootstrap credential");
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("atomically consumes a one-time token when multiple requests race", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const token = yield* bootstrapCredentials.issueOneTimeToken();
const results = yield* Effect.all(
Array.from({ length: 8 }, () =>
Effect.result(bootstrapCredentials.consume(token.credential)),
),
{
concurrency: "unbounded",
},
);
const successes = results.filter((result) => result._tag === "Success");
const failures = results.filter((result) => result._tag === "Failure");
expect(successes).toHaveLength(1);
expect(failures).toHaveLength(7);
for (const failure of failures) {
expect(failure.failure._tag).toBe("BootstrapCredentialError");
expect(failure.failure.message).toContain("Unknown bootstrap credential");
}
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(first.method).toBe("desktop-bootstrap");
expect(first.role).toBe("owner");
expect(first.subject).toBe("desktop-bootstrap");
expect(second._tag).toBe("BootstrapCredentialError");
expect(second.status).toBe(401);
}).pipe(
Effect.provide(
makeBootstrapCredentialLayer({
desktopBootstrapToken: "desktop-bootstrap-token",
}),
),
),
);
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
yield* TestClock.adjust(Duration.minutes(6));
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(expired._tag).toBe("BootstrapCredentialError");
expect(expired.status).toBe(401);
expect(expired.message).toContain("Bootstrap credential expired");
}).pipe(
Effect.provide(
Layer.merge(
makeBootstrapCredentialLayer({
desktopBootstrapToken: "desktop-bootstrap-token",
}),
TestClock.layer(),
),
),
),
);
it.effect("lists and revokes active pairing links", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const first = yield* bootstrapCredentials.issueOneTimeToken();
const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
const revoked = yield* bootstrapCredentials.revoke(first.id);
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
expect(revoked).toBe(true);
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
expect(revokedConsume.message).toContain("no longer available");
expect(revokedConsume.status).toBe(401);
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
});
@@ -0,0 +1,296 @@
import type { AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
import { Option } from "effect";
import { ServerConfig } from "../../config.ts";
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
import {
BootstrapCredentialError,
BootstrapCredentialService,
type BootstrapCredentialChange,
type BootstrapCredentialServiceShape,
type BootstrapGrant,
type IssuedBootstrapCredential,
} from "../Services/BootstrapCredentialService.ts";
interface StoredBootstrapGrant extends BootstrapGrant {
readonly remainingUses: number | "unbounded";
}
type ConsumeResult =
| {
readonly _tag: "error";
readonly reason: "not-found" | "expired";
readonly error: BootstrapCredentialError;
}
| {
readonly _tag: "success";
readonly grant: BootstrapGrant;
};
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const generatePairingToken = (): string => {
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
};
export const makeBootstrapCredentialService = Effect.gen(function* () {
const config = yield* ServerConfig;
const pairingLinks = yield* AuthPairingLinkRepository;
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
const invalidBootstrapCredentialError = (message: string) =>
new BootstrapCredentialError({
message,
status: 401,
});
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
new BootstrapCredentialError({
message,
status: 500,
cause,
});
const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
Ref.update(seededGrantsRef, (current) => {
const next = new Map(current);
next.set(credential, grant);
return next;
});
const emitUpsert = (pairingLink: AuthPairingLink) =>
PubSub.publish(changesPubSub, {
type: "pairingLinkUpserted",
pairingLink,
}).pipe(Effect.asVoid);
const emitRemoved = (id: string) =>
PubSub.publish(changesPubSub, {
type: "pairingLinkRemoved",
id,
}).pipe(Effect.asVoid);
if (config.desktopBootstrapToken) {
const now = yield* DateTime.now;
yield* seedGrant(config.desktopBootstrapToken, {
method: "desktop-bootstrap",
role: "owner",
subject: "desktop-bootstrap",
expiresAt: DateTime.add(now, {
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
}),
remainingUses: 1,
});
}
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
internalBootstrapCredentialError(message, cause);
const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const rows = yield* pairingLinks.listActive({ now });
return rows.map((row) =>
row.label
? ({
id: row.id,
credential: row.credential,
role: row.role,
subject: row.subject,
label: row.label,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
} satisfies AuthPairingLink)
: ({
id: row.id,
credential: row.credential,
role: row.role,
subject: row.subject,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
} satisfies AuthPairingLink),
);
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
Effect.gen(function* () {
const revokedAt = yield* DateTime.now;
const revoked = yield* pairingLinks.revoke({
id,
revokedAt,
});
if (revoked) {
yield* emitRemoved(id);
}
return revoked;
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
Effect.gen(function* () {
const id = crypto.randomUUID();
const credential = generatePairingToken();
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
id,
credential,
...(input?.label ? { label: input.label } : {}),
expiresAt,
};
yield* pairingLinks.create({
id,
credential,
method: "one-time-token",
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
label: input?.label ?? null,
createdAt: now,
expiresAt: expiresAt,
});
yield* emitUpsert({
id,
credential,
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(input?.label ? { label: input.label } : {}),
createdAt: now,
expiresAt,
});
return issued;
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const seededResult: ConsumeResult = yield* Ref.modify(
seededGrantsRef,
(current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
const grant = current.get(credential);
if (!grant) {
return [
{
_tag: "error",
reason: "not-found",
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
},
current,
];
}
const next = new Map(current);
if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
next.delete(credential);
return [
{
_tag: "error",
reason: "expired",
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
},
next,
];
}
const remainingUses = grant.remainingUses;
if (typeof remainingUses === "number") {
if (remainingUses <= 1) {
next.delete(credential);
} else {
next.set(credential, {
...grant,
remainingUses: remainingUses - 1,
});
}
}
return [
{
_tag: "success",
grant: {
method: grant.method,
role: grant.role,
subject: grant.subject,
...(grant.label ? { label: grant.label } : {}),
expiresAt: grant.expiresAt,
} satisfies BootstrapGrant,
},
next,
];
},
);
if (seededResult._tag === "success") {
return seededResult.grant;
}
if (seededResult.reason !== "not-found") {
return yield* seededResult.error;
}
const consumed = yield* pairingLinks.consumeAvailable({
credential,
consumedAt: now,
now,
});
if (Option.isSome(consumed)) {
yield* emitRemoved(consumed.value.id);
return {
method: consumed.value.method,
role: consumed.value.role,
subject: consumed.value.subject,
...(consumed.value.label ? { label: consumed.value.label } : {}),
expiresAt: consumed.value.expiresAt,
} satisfies BootstrapGrant;
}
const matching = yield* pairingLinks.getByCredential({ credential });
if (Option.isNone(matching)) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
}
if (matching.value.revokedAt !== null) {
return yield* invalidBootstrapCredentialError(
"Bootstrap credential is no longer available.",
);
}
if (matching.value.consumedAt !== null) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
}
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
}
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
}).pipe(
Effect.mapError((cause) =>
cause instanceof BootstrapCredentialError
? cause
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
),
);
return {
issueOneTimeToken,
listActive,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
revoke,
consume,
} satisfies BootstrapCredentialServiceShape;
});
export const BootstrapCredentialServiceLive = Layer.effect(
BootstrapCredentialService,
makeBootstrapCredentialService,
).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
@@ -0,0 +1,182 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
ServerAuthLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStoreLive),
Layer.provide(makeServerConfigLayer(overrides)),
);
const makeCookieRequest = (
sessionToken: string,
): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
({
cookies: {
t3_session: sessionToken,
},
headers: {},
}) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
const requestMetadata = {
deviceType: "desktop" as const,
os: "macOS",
browser: "Chrome",
ipAddress: "192.168.1.23",
};
it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
it.effect("maps invalid bootstrap credential failures to 401", () =>
Effect.sync(() => {
const error = toBootstrapExchangeAuthError(
new BootstrapCredentialError({
message: "Unknown bootstrap credential.",
status: 401,
}),
);
expect(error.status).toBe(401);
expect(error.message).toBe("Invalid bootstrap credential.");
}),
);
it.effect("maps unexpected bootstrap failures to 500", () =>
Effect.sync(() => {
const error = toBootstrapExchangeAuthError(
new BootstrapCredentialError({
message: "Failed to consume bootstrap credential.",
status: 500,
cause: new Error("sqlite is unavailable"),
}),
);
expect(error.status).toBe(500);
expect(error.message).toBe("Failed to validate bootstrap credential.");
}),
);
it.effect("issues client pairing credentials by default", () =>
Effect.gen(function* () {
const serverAuth = yield* ServerAuth;
const pairingCredential = yield* serverAuth.issuePairingCredential();
const exchanged = yield* serverAuth.exchangeBootstrapCredential(
pairingCredential.credential,
requestMetadata,
);
const verified = yield* serverAuth.authenticateHttpRequest(
makeCookieRequest(exchanged.sessionToken),
);
expect(verified.sessionId.length).toBeGreaterThan(0);
expect(verified.role).toBe("client");
expect(verified.subject).toBe("one-time-token");
}).pipe(Effect.provide(makeServerAuthLayer())),
);
it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
Effect.gen(function* () {
const serverAuth = yield* ServerAuth;
const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
const listedPairingLinks = yield* serverAuth.listPairingLinks();
expect(token).toBeTruthy();
expect(
listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
).toBe(false);
const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
const verified = yield* serverAuth.authenticateHttpRequest(
makeCookieRequest(exchanged.sessionToken),
);
expect(verified.role).toBe("owner");
expect(verified.subject).toBe("owner-bootstrap");
}).pipe(Effect.provide(makeServerAuthLayer())),
);
it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
Effect.gen(function* () {
const serverAuth = yield* ServerAuth;
const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
"desktop-bootstrap-token",
requestMetadata,
);
const ownerSession = yield* serverAuth.authenticateHttpRequest(
makeCookieRequest(ownerExchange.sessionToken),
);
const pairingCredential = yield* serverAuth.issuePairingCredential({
label: "Julius iPhone",
});
const listedPairingLinks = yield* serverAuth.listPairingLinks();
const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
pairingCredential.credential,
{
...requestMetadata,
deviceType: "mobile",
os: "iOS",
browser: "Safari",
ipAddress: "192.168.1.88",
},
);
const clientSession = yield* serverAuth.authenticateHttpRequest(
makeCookieRequest(clientExchange.sessionToken),
);
const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
"Julius iPhone",
);
expect(clientsBeforeRevoke).toHaveLength(2);
expect(
clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
).toBe(true);
expect(
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
).toBe(false);
expect(
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
.label,
).toBe("Julius iPhone");
expect(
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
.deviceType,
).toBe("mobile");
expect(revokedCount).toBe(1);
expect(clientsAfterRevoke).toHaveLength(1);
expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
}).pipe(
Effect.provide(
makeServerAuthLayer({
desktopBootstrapToken: "desktop-bootstrap-token",
}),
),
),
);
});
+385
View File
@@ -0,0 +1,385 @@
import {
type AuthBearerBootstrapResult,
type AuthClientSession,
type AuthBootstrapResult,
type AuthPairingCredentialResult,
type AuthSessionState,
type AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { DateTime, Effect, Layer, Option } from "effect";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
import {
ServerAuth,
type AuthenticatedSession,
AuthError,
type ServerAuthShape,
} from "../Services/ServerAuth.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
type BootstrapExchangeResult = {
readonly response: AuthBootstrapResult;
readonly sessionToken: string;
};
const AUTHORIZATION_PREFIX = "Bearer ";
const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
if (cause.status === 500) {
return new AuthError({
message: "Failed to validate bootstrap credential.",
status: 500,
cause,
});
}
return new AuthError({
message: "Invalid bootstrap credential.",
status: 401,
cause,
});
}
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
const header = request.headers["authorization"];
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
return null;
}
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
return token.length > 0 ? token : null;
}
export const makeServerAuth = Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const bootstrapCredentials = yield* BootstrapCredentialService;
const authControlPlane = yield* AuthControlPlane;
const sessions = yield* SessionCredentialService;
const descriptor = yield* policy.getDescriptor();
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
sessions.verify(token).pipe(
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
method: session.method,
role: session.role,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
Effect.mapError(
(cause) =>
new AuthError({
message: "Unauthorized request.",
status: 401,
cause,
}),
),
);
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
const cookieToken = request.cookies[sessions.cookieName];
const bearerToken = parseBearerToken(request);
const credential = cookieToken ?? bearerToken;
if (!credential) {
return Effect.fail(
new AuthError({
message: "Authentication required.",
status: 401,
}),
);
}
return authenticateToken(credential);
};
const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
authenticateRequest(request).pipe(
Effect.map(
(session) =>
({
authenticated: true,
auth: descriptor,
role: session.role,
sessionMethod: session.method,
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
}) satisfies AuthSessionState,
),
Effect.catchTag("AuthError", () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
),
);
const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
credential,
requestMetadata,
) =>
bootstrapCredentials.consume(credential).pipe(
Effect.mapError(toBootstrapExchangeAuthError),
Effect.flatMap((grant) =>
sessions
.issue({
method: "browser-session-cookie",
subject: grant.subject,
role: grant.role,
client: {
...requestMetadata,
...(grant.label ? { label: grant.label } : {}),
},
})
.pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to issue authenticated session.",
cause,
}),
),
),
),
Effect.map(
(session) =>
({
response: {
authenticated: true,
role: session.role,
sessionMethod: session.method,
expiresAt: DateTime.toUtc(session.expiresAt),
} satisfies AuthBootstrapResult,
sessionToken: session.token,
}) satisfies BootstrapExchangeResult,
),
);
const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
(credential, requestMetadata) =>
bootstrapCredentials.consume(credential).pipe(
Effect.mapError(toBootstrapExchangeAuthError),
Effect.flatMap((grant) =>
sessions
.issue({
method: "bearer-session-token",
subject: grant.subject,
role: grant.role,
client: {
...requestMetadata,
...(grant.label ? { label: grant.label } : {}),
},
})
.pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to issue authenticated session.",
cause,
}),
),
),
),
Effect.map(
(session) =>
({
authenticated: true,
role: session.role,
sessionMethod: "bearer-session-token",
expiresAt: DateTime.toUtc(session.expiresAt),
sessionToken: session.token,
}) satisfies AuthBearerBootstrapResult,
),
);
const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
authControlPlane
.createPairingLink({
role: input?.role ?? "client",
subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
...(input?.label ? { label: input.label } : {}),
})
.pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to issue pairing credential.",
cause,
}),
),
Effect.map(
(issued) =>
({
id: issued.id,
credential: issued.credential,
...(issued.label ? { label: issued.label } : {}),
expiresAt: issued.expiresAt,
}) satisfies AuthPairingCredentialResult,
),
);
const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
authControlPlane
.listPairingLinks({
role: "client",
excludeSubjects: ["owner-bootstrap"],
})
.pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to load pairing links.",
cause,
}),
),
);
const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
authControlPlane.revokePairingLink(id).pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to revoke pairing link.",
cause,
}),
),
);
const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
authControlPlane.listSessions().pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to load paired clients.",
cause,
}),
),
Effect.map((clientSessions) =>
clientSessions.map(
(clientSession): AuthClientSession => ({
...clientSession,
current: clientSession.sessionId === currentSessionId,
}),
),
),
);
const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
currentSessionId,
targetSessionId,
) =>
Effect.gen(function* () {
if (currentSessionId === targetSessionId) {
return yield* new AuthError({
message: "Use revoke other clients to keep the current owner session active.",
status: 403,
});
}
return yield* authControlPlane.revokeSession(targetSessionId).pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to revoke client session.",
cause,
}),
),
);
});
const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
currentSessionId,
) =>
authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to revoke other client sessions.",
cause,
}),
),
);
const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
issuePairingCredential({ role: "owner" }).pipe(
Effect.map((issued) => {
const url = new URL(baseUrl);
url.pathname = "/pair";
url.searchParams.delete("token");
url.hash = new URLSearchParams([["token", issued.credential]]).toString();
return url.toString();
}),
);
const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
sessions.issueWebSocketToken(session.sessionId).pipe(
Effect.mapError(
(cause) =>
new AuthError({
message: "Failed to issue websocket token.",
cause,
}),
),
Effect.map(
(issued) =>
({
token: issued.token,
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies AuthWebSocketTokenResult,
),
);
const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
Effect.gen(function* () {
const requestUrl = HttpServerRequest.toURL(request);
if (Option.isSome(requestUrl)) {
const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
if (websocketToken && websocketToken.trim().length > 0) {
return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
method: session.method,
role: session.role,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
Effect.mapError(
(cause) =>
new AuthError({
message: "Unauthorized request.",
status: 401,
cause,
}),
),
);
}
}
return yield* authenticateRequest(request);
});
return {
getDescriptor: () => Effect.succeed(descriptor),
getSessionState,
exchangeBootstrapCredential,
exchangeBootstrapCredentialForBearerSession,
issuePairingCredential,
listPairingLinks,
revokePairingLink,
listClientSessions,
revokeClientSession,
revokeOtherClientSessions,
authenticateHttpRequest: authenticateRequest,
authenticateWebSocketUpgrade,
issueWebSocketToken,
issueStartupPairingUrl,
} satisfies ServerAuthShape;
});
export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
Layer.provideMerge(AuthControlPlaneLive),
Layer.provideMerge(AuthCoreLive),
Layer.provideMerge(ServerAuthPolicyLive),
);
@@ -0,0 +1,111 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
ServerAuthPolicyLive.pipe(
Layer.provide(
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
),
),
);
it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
it.effect("uses desktop-managed-local policy for desktop mode", () =>
Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "desktop",
}),
),
),
);
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("remote-reachable");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "desktop",
host: "0.0.0.0",
}),
),
),
);
it.effect("uses loopback-browser policy for loopback web hosts", () =>
Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
}),
),
),
);
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("remote-reachable");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "web",
host: "0.0.0.0",
}),
),
),
);
it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
Effect.gen(function* () {
const policy = yield* ServerAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.policy).toBe("remote-reachable");
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "web",
host: "192.168.1.50",
}),
),
),
);
});
@@ -0,0 +1,41 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
export const makeServerAuthPolicy = Effect.gen(function* () {
const config = yield* ServerConfig;
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
const policy =
config.mode === "desktop"
? isRemoteReachable
? "remote-reachable"
: "desktop-managed-local"
: isRemoteReachable
? "remote-reachable"
: "loopback-browser";
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
policy === "desktop-managed-local"
? ["desktop-bootstrap"]
: config.mode === "desktop" && policy === "remote-reachable"
? ["desktop-bootstrap", "one-time-token"]
: ["one-time-token"];
const descriptor: ServerAuthDescriptor = {
policy,
bootstrapMethods,
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: SESSION_COOKIE_NAME,
};
return {
getDescriptor: () => Effect.succeed(descriptor),
} satisfies ServerAuthPolicyShape;
});
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
@@ -0,0 +1,263 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
const makeServerConfigLayer = () =>
ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
const makeServerSecretStoreLayer = () =>
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
const PermissionDeniedFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
readFile: (path) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: path,
description: "Permission denied while reading secret file.",
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makePermissionDeniedSecretStoreLayer = () =>
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(PermissionDeniedFileSystemLayer),
);
const RenameFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
rename: (from, to) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "rename",
pathOrDescriptor: `${String(from)} -> ${String(to)}`,
description: "Permission denied while persisting secret file.",
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeRenameFailureSecretStoreLayer = () =>
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(RenameFailureFileSystemLayer),
);
const RemoveFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
remove: (path, options) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "remove",
pathOrDescriptor: String(path),
description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeRemoveFailureSecretStoreLayer = () =>
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(RemoveFailureFileSystemLayer),
);
const ConcurrentReadMissFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const readCountRef = yield* Ref.make(0);
const readBarrier = yield* Deferred.make<void>();
return {
...fileSystem,
readFile: (path) =>
String(path).endsWith("/session-signing-key.bin")
? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
Effect.flatMap((count) => {
if (count > 2) {
return fileSystem.readFile(path);
}
return Effect.gen(function* () {
if (count === 2) {
yield* Deferred.succeed(readBarrier, void 0);
}
yield* Deferred.await(readBarrier);
return yield* Effect.failCause(
Cause.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: String(path),
description: "Secret file does not exist yet.",
}),
),
);
});
}),
)
: fileSystem.readFile(path),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeConcurrentCreateSecretStoreLayer = () =>
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
);
it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
it.effect("returns null when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const secret = yield* secretStore.get("missing-secret");
expect(secret).toBeNull();
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
it.effect("reuses an existing secret instead of regenerating it", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
expect(Array.from(second)).toEqual(Array.from(first));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
it.effect("returns the persisted secret when concurrent creators race", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const [first, second] = yield* Effect.all(
[
secretStore.getOrCreateRandom("session-signing-key", 32),
secretStore.getOrCreateRandom("session-signing-key", 32),
],
{ concurrency: "unbounded" },
);
const persisted = yield* secretStore.get("session-signing-key");
expect(persisted).not.toBeNull();
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);
it.effect("uses restrictive permissions for the secret directory and files", () =>
Effect.gen(function* () {
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
const recordingFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
makeDirectory: () => Effect.void,
writeFile: () => Effect.void,
rename: () => Effect.void,
chmod: (path, mode) =>
Effect.sync(() => {
chmodCalls.push({ path: String(path), mode });
}),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const secretStore = yield* Effect.service(ServerSecretStore).pipe(
Effect.provide(
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(recordingFileSystemLayer),
),
),
);
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
true,
);
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("propagates read failures other than missing-file errors", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
expect(error).toBeInstanceOf(SecretStoreError);
expect(error.message).toContain("Failed to read secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
);
it.effect("propagates write failures instead of treating them as success", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const error = yield* Effect.flip(
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
);
expect(error).toBeInstanceOf(SecretStoreError);
expect(error.message).toContain("Failed to persist secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
);
it.effect("propagates remove failures other than missing-file errors", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
expect(error).toBeInstanceOf(SecretStoreError);
expect(error.message).toContain("Failed to remove secret session-signing-key.");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
);
});
@@ -0,0 +1,151 @@
import * as Crypto from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
import {
SecretStoreError,
ServerSecretStore,
type ServerSecretStoreShape,
} from "../Services/ServerSecretStore.ts";
export const makeServerSecretStore = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
cause,
}),
),
);
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.catch((cause) =>
isMissingSecretFileError(cause)
? Effect.succeed(null)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name}.`,
cause,
}),
),
),
);
const set: ServerSecretStoreShape["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
return Effect.gen(function* () {
yield* fileSystem.writeFile(tempPath, value);
yield* fileSystem.chmod(tempPath, 0o600);
yield* fileSystem.rename(tempPath, secretPath);
yield* fileSystem.chmod(secretPath, 0o600);
}).pipe(
Effect.catch((cause) =>
fileSystem.remove(tempPath).pipe(
Effect.ignore,
Effect.flatMap(() =>
Effect.fail(
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
cause,
}),
),
),
),
),
);
};
const create: ServerSecretStoreShape["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
return Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(secretPath, {
flag: "wx",
mode: 0o600,
});
yield* file.writeAll(value);
yield* file.sync;
yield* fileSystem.chmod(secretPath, 0o600);
}),
).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
cause,
}),
),
);
};
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
Effect.flatMap((existing) => {
if (existing) {
return Effect.succeed(existing);
}
const generated = Crypto.randomBytes(bytes);
return create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isAlreadyExistsSecretFileError(error.cause)
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
? Effect.succeed(created)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
),
)
: Effect.fail(error),
),
);
}),
);
const remove: ServerSecretStoreShape["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
isMissingSecretFileError(cause)
? Effect.void
: Effect.fail(
new SecretStoreError({
message: `Failed to remove secret ${name}.`,
cause,
}),
),
),
);
return {
get,
set,
getOrCreateRandom,
remove,
} satisfies ServerSecretStoreShape;
});
export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
@@ -0,0 +1,191 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
const makeSessionCredentialLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
SessionCredentialServiceLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStoreLive),
Layer.provide(makeServerConfigLayer(overrides)),
);
it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
it.effect("issues and verifies signed browser session tokens", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const issued = yield* sessions.issue({
subject: "desktop-bootstrap",
role: "owner",
client: {
label: "Desktop app",
deviceType: "desktop",
os: "macOS",
browser: "Electron",
ipAddress: "127.0.0.1",
},
});
const verified = yield* sessions.verify(issued.token);
expect(verified.method).toBe("browser-session-cookie");
expect(verified.subject).toBe("desktop-bootstrap");
expect(verified.role).toBe("owner");
expect(verified.client.label).toBe("Desktop app");
expect(verified.client.browser).toBe("Electron");
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
}).pipe(Effect.provide(makeSessionCredentialLayer())),
);
it.effect("rejects malformed session tokens", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
expect(error._tag).toBe("SessionCredentialError");
expect(error.message).toContain("Malformed session token");
}).pipe(Effect.provide(makeSessionCredentialLayer())),
);
it.effect("verifies session tokens against the Effect clock", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const issued = yield* sessions.issue({
method: "bearer-session-token",
subject: "test-clock",
});
const verified = yield* sessions.verify(issued.token);
expect(verified.method).toBe("bearer-session-token");
expect(verified.subject).toBe("test-clock");
expect(verified.role).toBe("client");
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
);
it.effect("rejects websocket tokens once the parent session has expired", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const issued = yield* sessions.issue({
method: "bearer-session-token",
subject: "short-lived",
ttl: Duration.seconds(1),
});
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
yield* TestClock.adjust(Duration.seconds(2));
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(error.message).toContain("expired");
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
);
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const owner = yield* sessions.issue({
subject: "desktop-bootstrap",
role: "owner",
client: {
label: "Desktop app",
deviceType: "desktop",
os: "macOS",
browser: "Electron",
},
});
const client = yield* sessions.issue({
subject: "one-time-token",
role: "client",
client: {
label: "Julius iPhone",
deviceType: "mobile",
os: "iOS",
browser: "Safari",
ipAddress: "192.168.1.88",
},
});
yield* sessions.markConnected(client.sessionId);
const beforeRevoke = yield* sessions.listActive();
const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
const afterRevoke = yield* sessions.listActive();
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
expect(beforeRevoke).toHaveLength(2);
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
true,
);
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
"Julius iPhone",
);
expect(
beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
).toBe("desktop");
expect(revokedCount).toBe(1);
expect(afterRevoke).toHaveLength(1);
expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
expect(revokedClient.message).toContain("revoked");
}).pipe(Effect.provide(makeSessionCredentialLayer())),
);
it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
Effect.gen(function* () {
const sessions = yield* SessionCredentialService;
const issued = yield* sessions.issue({
subject: "reconnect-test",
method: "bearer-session-token",
});
const beforeConnect = yield* sessions.listActive();
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
yield* TestClock.adjust(Duration.seconds(1));
yield* sessions.markConnected(issued.sessionId);
const firstConnect = yield* sessions.listActive();
const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
expect(firstConnect[0]?.connected).toBe(true);
expect(firstConnectedAt).not.toBeNull();
yield* TestClock.adjust(Duration.seconds(1));
yield* sessions.markConnected(issued.sessionId);
const stillConnected = yield* sessions.listActive();
expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
yield* sessions.markDisconnected(issued.sessionId);
yield* sessions.markDisconnected(issued.sessionId);
const afterDisconnect = yield* sessions.listActive();
expect(afterDisconnect[0]?.connected).toBe(false);
expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
yield* TestClock.adjust(Duration.seconds(1));
yield* sessions.markConnected(issued.sessionId);
const afterReconnect = yield* sessions.listActive();
expect(afterReconnect[0]?.connected).toBe(true);
expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
);
});
@@ -0,0 +1,494 @@
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
import { Option } from "effect";
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import {
SessionCredentialError,
SessionCredentialService,
type IssuedSession,
type SessionCredentialChange,
type SessionCredentialServiceShape,
type VerifiedSession,
} from "../Services/SessionCredentialService.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../utils.ts";
const SIGNING_SECRET_NAME = "server-signing-key";
const DEFAULT_SESSION_TTL = Duration.days(30);
const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
const SessionClaims = Schema.Struct({
v: Schema.Literal(1),
kind: Schema.Literal("session"),
sid: AuthSessionId,
sub: Schema.String,
role: Schema.Literals(["owner", "client"]),
method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
iat: Schema.Number,
exp: Schema.Number,
});
type SessionClaims = typeof SessionClaims.Type;
const WebSocketClaims = Schema.Struct({
v: Schema.Literal(1),
kind: Schema.Literal("websocket"),
sid: AuthSessionId,
iat: Schema.Number,
exp: Schema.Number,
});
type WebSocketClaims = typeof WebSocketClaims.Type;
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
function createDefaultClientMetadata(): AuthClientMetadata {
return {
deviceType: "unknown",
};
}
function toClientMetadata(record: {
readonly label: string | null;
readonly ipAddress: string | null;
readonly userAgent: string | null;
readonly deviceType: AuthClientMetadata["deviceType"];
readonly os: string | null;
readonly browser: string | null;
}): AuthClientMetadata {
return {
...(record.label ? { label: record.label } : {}),
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
...(record.userAgent ? { userAgent: record.userAgent } : {}),
deviceType: record.deviceType,
...(record.os ? { os: record.os } : {}),
...(record.browser ? { browser: record.browser } : {}),
};
}
function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
return {
...input,
current: false,
};
}
export const makeSessionCredentialService = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const authSessions = yield* AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const toSessionCredentialError = (message: string) => (cause: unknown) =>
new SessionCredentialError({
message,
cause,
});
const emitUpsert = (clientSession: AuthClientSession) =>
PubSub.publish(changesPubSub, {
type: "clientUpserted",
clientSession,
}).pipe(Effect.asVoid);
const emitRemoved = (sessionId: AuthSessionId) =>
PubSub.publish(changesPubSub, {
type: "clientRemoved",
sessionId,
}).pipe(Effect.asVoid);
const loadActiveSession = (sessionId: AuthSessionId) =>
Effect.gen(function* () {
const row = yield* authSessions.getById({ sessionId });
if (Option.isNone(row) || row.value.revokedAt !== null) {
return Option.none<AuthClientSession>();
}
const connectedSessions = yield* Ref.get(connectedSessionsRef);
return Option.some(
toAuthClientSession({
sessionId: row.value.sessionId,
subject: row.value.subject,
role: row.value.role,
method: row.value.method,
client: toClientMetadata(row.value.client),
issuedAt: row.value.issuedAt,
expiresAt: row.value.expiresAt,
lastConnectedAt: row.value.lastConnectedAt,
connected: connectedSessions.has(row.value.sessionId),
}),
);
});
const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
Ref.modify(connectedSessionsRef, (current) => {
const next = new Map(current);
const wasDisconnected = !next.has(sessionId);
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
return [wasDisconnected, next] as const;
}).pipe(
Effect.flatMap((wasDisconnected) =>
wasDisconnected
? DateTime.now.pipe(
Effect.flatMap((lastConnectedAt) =>
authSessions.setLastConnectedAt({
sessionId,
lastConnectedAt,
}),
),
)
: Effect.void,
),
Effect.flatMap(() => loadActiveSession(sessionId)),
Effect.flatMap((session) =>
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logError("Failed to publish connected-session auth update.").pipe(
Effect.annotateLogs({
sessionId,
cause,
}),
),
),
);
const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
const remaining = (next.get(sessionId) ?? 0) - 1;
if (remaining > 0) {
next.set(sessionId, remaining);
} else {
next.delete(sessionId);
}
return next;
}).pipe(
Effect.flatMap(() => loadActiveSession(sessionId)),
Effect.flatMap((session) =>
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
Effect.annotateLogs({
sessionId,
cause,
}),
),
),
);
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
});
const claims: SessionClaims = {
v: 1,
kind: "session",
sid: sessionId,
sub: input?.subject ?? "browser",
role: input?.role ?? "client",
method: input?.method ?? "browser-session-cookie",
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
const signature = signPayload(encodedPayload, signingSecret);
const client = input?.client ?? createDefaultClientMetadata();
yield* authSessions.create({
sessionId,
subject: claims.sub,
role: claims.role,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
});
yield* emitUpsert(
toAuthClientSession({
sessionId,
subject: claims.sub,
role: claims.role,
method: claims.method,
client,
issuedAt,
expiresAt,
lastConnectedAt: null,
connected: false,
}),
);
return {
sessionId,
token: `${encodedPayload}.${signature}`,
method: claims.method,
client,
expiresAt: expiresAt,
role: claims.role,
} satisfies IssuedSession;
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
const verify: SessionCredentialServiceShape["verify"] = (token) =>
Effect.gen(function* () {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new SessionCredentialError({
message: "Malformed session token.",
});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new SessionCredentialError({
message: "Invalid session token signature.",
});
}
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialError({
message: "Invalid session token payload.",
cause,
}),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionCredentialError({
message: "Session token expired.",
});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new SessionCredentialError({
message: "Unknown session token.",
});
}
if (row.value.revokedAt !== null) {
return yield* new SessionCredentialError({
message: "Session token revoked.",
});
}
return {
sessionId: claims.sid,
token,
method: claims.method,
client: toClientMetadata(row.value.client),
expiresAt: DateTime.makeUnsafe(claims.exp),
subject: claims.sub,
role: claims.role,
} satisfies VerifiedSession;
}).pipe(
Effect.mapError((cause) =>
cause instanceof SessionCredentialError
? cause
: new SessionCredentialError({
message: "Failed to verify session credential.",
cause,
}),
),
);
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
sessionId,
input,
) =>
Effect.gen(function* () {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
Effect.gen(function* () {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new SessionCredentialError({
message: "Malformed websocket token.",
});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new SessionCredentialError({
message: "Invalid websocket token signature.",
});
}
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialError({
message: "Invalid websocket token payload.",
cause,
}),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionCredentialError({
message: "Websocket token expired.",
});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new SessionCredentialError({
message: "Unknown websocket session.",
});
}
if (row.value.expiresAt.epochMilliseconds <= now) {
return yield* new SessionCredentialError({
message: "Websocket session expired.",
});
}
if (row.value.revokedAt !== null) {
return yield* new SessionCredentialError({
message: "Websocket session revoked.",
});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
expiresAt: row.value.expiresAt,
subject: row.value.subject,
role: row.value.role,
} satisfies VerifiedSession;
}).pipe(
Effect.mapError((cause) =>
cause instanceof SessionCredentialError
? cause
: new SessionCredentialError({
message: "Failed to verify websocket token.",
cause,
}),
),
);
const listActive: SessionCredentialServiceShape["listActive"] = () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const connectedSessions = yield* Ref.get(connectedSessionsRef);
const rows = yield* authSessions.listActive({ now });
return rows.map((row) =>
toAuthClientSession({
sessionId: row.sessionId,
subject: row.subject,
role: row.role,
method: row.method,
client: toClientMetadata(row.client),
issuedAt: row.issuedAt,
expiresAt: row.expiresAt,
lastConnectedAt: row.lastConnectedAt,
connected: connectedSessions.has(row.sessionId),
}),
);
}).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
Effect.gen(function* () {
const revokedAt = yield* DateTime.now;
const revoked = yield* authSessions.revoke({
sessionId,
revokedAt,
});
if (revoked) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
next.delete(sessionId);
return next;
});
yield* emitRemoved(sessionId);
}
return revoked;
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
Effect.gen(function* () {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions.revokeAllExcept({
currentSessionId: sessionId,
revokedAt,
});
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
return {
cookieName: SESSION_COOKIE_NAME,
issue,
verify,
issueWebSocketToken,
verifyWebSocketToken,
listActive,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
revoke,
revokeAllExcept,
markConnected,
markDisconnected,
} satisfies SessionCredentialServiceShape;
});
export const SessionCredentialServiceLive = Layer.effect(
SessionCredentialService,
makeSessionCredentialService,
).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
@@ -0,0 +1,69 @@
import type {
AuthClientMetadata,
AuthClientSession,
AuthPairingLink,
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
import { SessionRole } from "./SessionCredentialService";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export interface IssuedPairingLink {
readonly id: string;
readonly credential: string;
readonly role: SessionRole;
readonly subject: string;
readonly label?: string;
readonly createdAt: DateTime.Utc;
readonly expiresAt: DateTime.Utc;
}
export interface IssuedBearerSession {
readonly sessionId: AuthSessionId;
readonly token: string;
readonly method: "bearer-session-token";
readonly role: SessionRole;
readonly subject: string;
readonly client: AuthClientMetadata;
readonly expiresAt: DateTime.Utc;
}
export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface AuthControlPlaneShape {
readonly createPairingLink: (input?: {
readonly ttl?: Duration.Duration;
readonly label?: string;
readonly role?: SessionRole;
readonly subject?: string;
}) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
readonly listPairingLinks: (input?: {
readonly role?: SessionRole;
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly role?: SessionRole;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
AuthControlPlaneError
>;
readonly revokeSession: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, AuthControlPlaneError>;
readonly revokeOtherSessionsExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, AuthControlPlaneError>;
}
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
"t3/AuthControlPlane",
) {}
@@ -0,0 +1,57 @@
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export type BootstrapCredentialRole = "owner" | "client";
export interface BootstrapGrant {
readonly method: ServerAuthBootstrapMethod;
readonly role: BootstrapCredentialRole;
readonly subject: string;
readonly label?: string;
readonly expiresAt: DateTime.DateTime;
}
export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
readonly message: string;
readonly status?: 401 | 500;
readonly cause?: unknown;
}> {}
export interface IssuedBootstrapCredential {
readonly id: string;
readonly credential: string;
readonly label?: string;
readonly expiresAt: DateTime.Utc;
}
export type BootstrapCredentialChange =
| {
readonly type: "pairingLinkUpserted";
readonly pairingLink: AuthPairingLink;
}
| {
readonly type: "pairingLinkRemoved";
readonly id: string;
};
export interface BootstrapCredentialServiceShape {
readonly issueOneTimeToken: (input?: {
readonly ttl?: Duration.Duration;
readonly role?: BootstrapCredentialRole;
readonly subject?: string;
readonly label?: string;
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthPairingLink>,
BootstrapCredentialError
>;
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
}
export class BootstrapCredentialService extends ServiceMap.Service<
BootstrapCredentialService,
BootstrapCredentialServiceShape
>()("t3/auth/Services/BootstrapCredentialService") {}
@@ -0,0 +1,84 @@
import type {
AuthBearerBootstrapResult,
AuthBootstrapResult,
AuthClientMetadata,
AuthClientSession,
AuthCreatePairingCredentialInput,
AuthPairingLink,
AuthPairingCredentialResult,
AuthSessionId,
AuthSessionState,
ServerAuthDescriptor,
ServerAuthSessionMethod,
AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { Data, DateTime, ServiceMap } from "effect";
import type { Effect } from "effect";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import type { SessionRole } from "./SessionCredentialService.ts";
export interface AuthenticatedSession {
readonly sessionId: AuthSessionId;
readonly subject: string;
readonly method: ServerAuthSessionMethod;
readonly role: SessionRole;
readonly expiresAt?: DateTime.DateTime;
}
export class AuthError extends Data.TaggedError("AuthError")<{
readonly message: string;
readonly status?: 400 | 401 | 403 | 500;
readonly cause?: unknown;
}> {}
export interface ServerAuthShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
readonly getSessionState: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthSessionState, never>;
readonly exchangeBootstrapCredential: (
credential: string,
requestMetadata: AuthClientMetadata,
) => Effect.Effect<
{
readonly response: AuthBootstrapResult;
readonly sessionToken: string;
},
AuthError
>;
readonly exchangeBootstrapCredentialForBearerSession: (
credential: string,
requestMetadata: AuthClientMetadata,
) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput & {
readonly role?: SessionRole;
},
) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
readonly listClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
readonly revokeClientSession: (
currentSessionId: AuthSessionId,
targetSessionId: AuthSessionId,
) => Effect.Effect<boolean, AuthError>;
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, AuthError>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, AuthError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, AuthError>;
readonly issueWebSocketToken: (
session: AuthenticatedSession,
) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
}
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
"t3/auth/Services/ServerAuth",
) {}
@@ -0,0 +1,11 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ServerAuthPolicyShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
}
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
"t3/auth/Services/ServerAuthPolicy",
) {}
@@ -0,0 +1,22 @@
import { Data, ServiceMap } from "effect";
import type { Effect } from "effect";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface ServerSecretStoreShape {
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
export class ServerSecretStore extends ServiceMap.Service<
ServerSecretStore,
ServerSecretStoreShape
>()("t3/auth/Services/ServerSecretStore") {}
@@ -0,0 +1,87 @@
import type {
AuthClientMetadata,
AuthClientSession,
AuthSessionId,
ServerAuthSessionMethod,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export type SessionRole = "owner" | "client";
export interface IssuedSession {
readonly sessionId: AuthSessionId;
readonly token: string;
readonly method: ServerAuthSessionMethod;
readonly client: AuthClientMetadata;
readonly expiresAt: DateTime.DateTime;
readonly role: SessionRole;
}
export interface VerifiedSession {
readonly sessionId: AuthSessionId;
readonly token: string;
readonly method: ServerAuthSessionMethod;
readonly client: AuthClientMetadata;
readonly expiresAt?: DateTime.DateTime;
readonly subject: string;
readonly role: SessionRole;
}
export type SessionCredentialChange =
| {
readonly type: "clientUpserted";
readonly clientSession: AuthClientSession;
}
| {
readonly type: "clientRemoved";
readonly sessionId: AuthSessionId;
};
export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface SessionCredentialServiceShape {
readonly cookieName: string;
readonly issue: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly method?: ServerAuthSessionMethod;
readonly role?: SessionRole;
readonly client?: AuthClientMetadata;
}) => Effect.Effect<IssuedSession, SessionCredentialError>;
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly issueWebSocketToken: (
sessionId: AuthSessionId,
input?: {
readonly ttl?: Duration.Duration;
},
) => Effect.Effect<
{
readonly token: string;
readonly expiresAt: DateTime.DateTime;
},
SessionCredentialError
>;
readonly verifyWebSocketToken: (
token: string,
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
SessionCredentialError
>;
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
readonly revokeAllExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, SessionCredentialError>;
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
}
export class SessionCredentialService extends ServiceMap.Service<
SessionCredentialService,
SessionCredentialServiceShape
>()("t3/auth/Services/SessionCredentialService") {}
Loaded 100 of 638 files, more files were not shown because too many files have changed in this diff. Show more