Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge e0a2f75d74 Add after recording for provider dialog optimization
Co-authored-by: Julius Marminge <[email protected]>
2026-05-27 16:12:52 +00:00
Cursor AgentandJulius Marminge 1ea8881b31 Optimize provider instance dialog renders
Co-authored-by: Julius Marminge <[email protected]>
2026-05-27 16:12:12 +00:00
Adam Buchweitz 4f0f24f055 fix: maintain reasoning selections for multiple providers (#2760) 2026-05-22 07:02:35 -07:00
t3-code[bot] d1e85c4e8f chore(release): prepare v0.0.24 2026-05-15 06:40:13 +00:00
Julius Marminge ea20e80021 Exclude workspace packages from desktop runtime deps (#2688) 2026-05-14 07:32:48 +00:00
Julius MarmingeandJulius Marminge 9e632f5cec [codex] add diagnostics resource history (#2685)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-14 09:14:32 +02:00
Julius Marminge 4120e94598 Back off VCS remote refresh failures (#2686) 2026-05-14 08:41:02 +02:00
Theo Browne 34bb18c8cf feat(marketing): Made marketing site less cringe (#2681) 2026-05-13 18:31:06 -07:00
Julius Marminge 90eea047a9 Skip healthy env reconnects after browser resume (#2677) 2026-05-13 22:29:36 +02:00
Julius Marminge f92e1e1b06 Simplify workspace package builds and deps (#2676) 2026-05-13 21:35:01 +02:00
Julius Marminge 556c42452c Harden GitHub workflow permissions
- Restrict release workflow defaults to read-only access
- Grant `id-token` only to the publish job
- Document safe handling for `pull_request_target` in PR size checks
2026-05-13 14:19:18 +02:00
Julius Marminge 7e20b23e7e Constrain provider update popover overflow (#2669) 2026-05-13 10:23:31 +02:00
Julius Marminge b83e9c95e4 Refactor composer refs and context providers (#2664) 2026-05-12 21:54:28 +02:00
a41f4895ce Reduce chat timeline activity rerenders (#2660)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-12 20:56:03 +02:00
d15909af15 Use Effect child process for editor launches (#2659)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-12 20:15:11 +02:00
447236d51f Stabilize project grouping settings selector (#2629)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-11 10:07:50 +00:00
legsandJulius Marminge 5165b8c333 Optimize VCS diff loading to be up to 98% faster (#2586)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-11 12:07:26 +02:00
Julius Marmingeandcodex 8fc317939f Preserve Codex probe results across scoped teardown (#2638)
Co-authored-by: codex <[email protected]>
2026-05-11 10:48:19 +02:00
Julius Marminge 16c69ba7ff Remove outline styling from git success toast action (#2639) 2026-05-11 08:45:40 +00:00
Julius Marminge e64c19f1af Alias stable releases to the router domain (#2636) 2026-05-11 10:41:32 +02:00
Utkarsh Patil 6ab8f93a23 fix(codex): use longer and shared auth probe timeout for provider status check (#2616) 2026-05-11 00:29:56 -07:00
t3-code[bot] b793401aee chore(release): prepare v0.0.23 2026-05-09 22:22:22 +00:00
Julius MarmingeandJulius Marminge 3c32bc8fd1 [codex] Fix hosted channel bootstrap (#2613)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:57:16 -07:00
Julius MarmingeandJulius Marminge 6efdf67e15 [codex] Fix Vercel Turbo env forwarding (#2612)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:09:40 -07:00
Julius MarmingeandJulius Marminge 39371c6012 [codex] Fix Vercel release web deploy scope (#2611)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:01:57 -07:00
Kainoa NewtonandJulius Marminge 99efaa0faa Collapse long user messages by default (#2180)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 02:00:03 +00:00
Julius Marminge 6b9feb1bd3 Update deployment command in release workflow (#2610) 2026-05-08 18:30:44 -07:00
Ben Vargas e0f3abd1a4 Fix remote pairing CORS responses (#2594) 2026-05-08 23:52:47 +00:00
34ec8a86fb [codex] add configurable automatic git fetch interval (#2605)
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-05-08 16:41:55 -07:00
932df4ed17 fix(ssh): fix reconnect issues and node binary path resolution (#2504)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-08 16:17:29 -07:00
Julius MarmingeandCursor Agent 63859aa072 perf: Add archived shell snapshot support (#2593)
Co-authored-by: Cursor Agent <[email protected]>
2026-05-08 15:49:41 -07:00
Julius MarmingeandJulius Marminge 7bfacd55d8 [codex] Handle NuGet provider bootstrap failures (#2608)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 15:20:02 -07:00
Kiri110K 271d65e047 Fix OpenCode raw text delta assembly (#2526) 2026-05-08 13:00:24 -07:00
aa8b9f2286 Deploy hosted web app from release workflow (#2507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-08 12:47:08 -07:00
Julius MarmingeandJulius Marminge 073eb389d3 [codex] Fix Windows release signing setup (#2606)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 12:35:52 -07:00
Julius Marmingeandcodex 825263b6f9 Scaffold oxlint plugin with initial rule (#2603)
Co-authored-by: codex <[email protected]>
2026-05-08 11:52:19 -07:00
Julius MarmingeandCursor Agent 25b02f4ba2 Enable stricter Effect LSP rules (#2596)
Co-authored-by: Cursor Agent <[email protected]>
2026-05-08 09:58:29 -07:00
Julius Marminge 131234be3f Match sticky changed-files header tint to card background (#2592) 2026-05-08 05:16:27 +00:00
7455472c34 Reduce sidebar selection rerenders (#2560)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-07 21:44:30 -07:00
Julius Marminge 9d919d0bb8 Move desktop server exposure logic into backend (#2591) 2026-05-08 04:25:33 +00:00
aa219be713 port desktop app to Effect (#2546)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-07 21:17:08 -07:00
Julius Marminge dd32f52655 Refresh Codex protocol bindings and adapter mappings (#2590) 2026-05-07 19:47:20 -07:00
Julius Marmingeandcodex 31b52acc8d [codex] Fix sidebar preview settings reset (#2587)
Co-authored-by: codex <[email protected]>
2026-05-07 17:24:40 -07:00
466d8ee5b0 feat(web): add configurable sidebar thread preview count (#1856)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-07 17:12:59 -07:00
maria 11f40556de feat(web): render skill calls as inline chips (#2572) 2026-05-07 14:43:16 -07:00
1bcfc88f58 Adopt idiomatic Effect APIs in generator and decider (#2581)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-07 12:19:32 -07:00
2ba58076fa Avoid timeline timer rerender commits (#2580)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-07 11:54:46 -07:00
maria c27109cc20 feat(web): mention skills in composer placeholder (#2570) 2026-05-07 10:51:32 -07:00
Julius Marminge a74ed8ed32 Revert "Cache desktop build assets in CI and release workflows" (#2568) 2026-05-06 23:04:28 +00:00
6c79039ce7 Cache desktop build assets in CI and release workflows (#2543)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-05-06 13:55:37 -07:00
Julius Marmingeandcodex 449e1aaa48 Make changed-files header sticky in chat timeline (#2565)
Co-authored-by: codex <[email protected]>
2026-05-06 13:24:34 -07:00
22384ae977 Adopt Effect JSON and DateTime idioms (#2559)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-06 10:36:25 -07:00
Julius MarmingeandJulius Marminge 499f1463d5 Split server CLI into focused submodules (#2545)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 23:02:05 -07:00
a2ff50dbba Add process and trace diagnostics views (#2532)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-05-06 04:22:50 +00:00
Minigamer42 166bce0389 Feature/intellij editors (#2475) 2026-05-06 04:12:52 +00:00
1498335e39 Optimize MessagesTimeline work row stability (#2527)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:57:33 -07:00
Julius MarmingeandJulius Marminge 25c9d267ac Stabilize git workspace and terminal tests (#2540)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:31:44 -07:00
536dcad19e Reduce timeline row rerenders (#2498)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:26:38 -07:00
Julius Marmingeandcodex 0e38870647 Add keybindings settings editor (#2533)
Co-authored-by: codex <[email protected]>
2026-05-06 00:08:52 +00:00
9b604bcae1 provider update advisories (#2312)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-05 15:59:51 -07:00
t3-code[bot] 35721d9a08 chore(release): prepare v0.0.22 2026-05-05 01:09:49 +00:00
shivamandJulius Marminge f4c9418d40 Add collapsible file diffs + @pierre/diffs version update. (#2502)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 17:06:07 -07:00
PeterandPeter van der Heijden 02dd47ea31 Fix repeated effect-language-service prepare hooks during bun install (#2497)
Co-authored-by: Peter van der Heijden <[email protected]>
2026-05-04 22:56:59 +00:00
legsandJulius Marminge aca0fa4e5b reduce startup time by ~47% and memory usage by up to 150-300MB (#2204)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 13:56:01 -07:00
Julius Marminge 0576820755 Prevent focus-ring clipping in AnimatedHeight (#2503) 2026-05-04 20:50:30 +00:00
Anirudh Vempati cb3211c8f3 README: Add OpenCode to first mention of supported agents (#2436) 2026-05-04 20:17:47 +00:00
Julius MarmingeandJulius Marminge 826965978b bitubicket base brnach (#2500)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 10:02:25 -07:00
623e471a02 Fix markdown highlight render stability (#2479)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 09:38:17 -07:00
91a03e0747 feat(source-control): add Bitbucket & Azure Devops providers (#2473)
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-05-04 00:59:58 -07:00
Julius Marminge d501ebe877 fix version test (#2490) 2026-05-04 05:27:18 +00:00
Julius Marmingeandcodex 3772fa127c feat: Hosted Frontend, Tailscale Integration & SSH Lancher (#2361)
Co-authored-by: codex <[email protected]>
2026-05-03 22:19:15 -07:00
92e340d80c feat(web): collapse mobile composer by default (#1263)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-03 19:48:10 -07:00
d7969264de Add remote repository publish and discovery support (#2482)
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-05-03 18:05:46 -07:00
Illia Panasenko f7748a0d65 feat: add "hide whitespace changes" option for diffs (#2389) 2026-05-03 11:47:37 -07:00
Julius MarmingeandJulius Marminge 0ce7e56e43 feat(scm): Gitlab (#2462)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 18:59:47 -07:00
Julius MarmingeandJulius Marminge 350d76ee14 [codex] Align GitHub source control adapter errors (#2476)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 16:59:03 -07:00
6d7fe2eeb7 Introduce pluggable VCS driver foundation (#2435)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-02 16:08:17 -07:00
Julius MarmingeandJulius Marminge 460d9c3eb9 Refactor provider settings to declarative metadata (#2452)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 14:14:34 -07:00
Ishan cb8015a34d fix(claude-agent): opt into claude_code system prompt preset (#2472) 2026-05-02 12:38:42 -07:00
Saikrishna Ambeti 8f50ca8e2c fix(web): show friendly error for invalid pairing token (#2222) 2026-05-02 12:23:26 -07:00
Julius MarmingeandJulius Marminge 4ceabac764 Fix dialog footer button clipping in Git actions dialog (#2458)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 23:57:44 -07:00
Julius MarmingeandJulius Marminge 7a3f21e7ca [codex] fix Discord release version flag (#2449)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 18:39:41 +00:00
Julius MarmingeandJulius Marminge 17b43960e8 Add structured Discord webhook logging for release notifications (#2431)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 03:53:47 +00:00
Julius MarmingeandJulius Marminge e5c7ac5a8c Optimize release workflow job execution (#2430)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 20:08:11 -07:00
a480f07241 Add Discord release announcements (#2429)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 19:13:05 -07:00
Adam Mansfield 1eb6fcea84 fix: opencode is not on PATH on Windows (#2183) 2026-04-30 18:15:45 -07:00
4ef361da73 fix(mobile): enable touch scrolling in file picker modal (#2420)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:12:48 -07:00
Noah Gregory c07ac592d8 fix: bump electron version to v40.9.3 and add it to our trusted dependencies (#2427) 2026-04-30 17:34:21 -07:00
d649ccf715 fix(web): respect iOS safe areas across mobile chrome & other mobile layout fixes (#2392)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 16:26:36 -07:00
shivam f54f4385e5 Narrow the right sidebar and update task panel and diff panel (#2409) 2026-04-30 15:33:06 -07:00
Julius Marminge e25ce07cc2 Add new GitHub users to VOUCHED.td (#2425) 2026-04-30 18:58:31 +00:00
532a1d891d fix(web): make thread archive button always visible on mobile (#2423)
Co-authored-by: Claude Sonnet 4.7 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:46:05 +00:00
9e2f7129e3 fix(web): make new thread button always visible on mobile (#2419)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:18:12 +00:00
a4298f1ceb fix(web): hide mobile sidebar after thread selection or creation (#1293)
Co-authored-by: Murat Aslan <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 11:10:37 -07:00
kp 86c94b4852 fix(web): allow closing diff panel in non-git projects (#2413) 2026-04-30 04:36:05 +00:00
Guilherme Vieira 69d9a659a3 fix(git): hide stale merged/closed PRs on the default branch (#1966) 2026-04-29 21:29:48 -07:00
9acf46a76d fix(web): prevent iOS Safari auto-zoom on input focus (#1652)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-29 18:03:40 -07:00
Bas Milius 44b39fe2ec fix(server): key AskUserQuestion answers by question text (#2404) 2026-04-29 17:44:44 -07:00
Julius Marmingeandcodex 02903f2db8 [codex] fix terminal dimension validation (#2411)
Co-authored-by: codex <[email protected]>
2026-04-30 00:09:00 +00:00
Julius Marmingeandcodex 22b7d8c524 [codex] Fix visited timestamp under clock skew (#2408)
Co-authored-by: codex <[email protected]>
2026-04-29 17:07:21 -07:00
pomp fe2fde5172 Add OpenCode to README (#2154) 2026-04-29 23:49:49 +00:00
zurielbm 7da6522fb8 fix: updated UI "add project" icon to match the command pallete icon (#2176) 2026-04-29 23:48:08 +00:00
08e6d4cfbf feat: Multi-Provider support (#2277)
Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-29 16:13:55 -07:00
Josh Meads 35822884d1 Stop OpenCode refresh from leaking serve processes
OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes.

Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle.
Rejected: Disable provider refresh | would hide model and auth state changes.
Confidence: high
Scope-risk: narrow
Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts
Tested: bun fmt
Tested: bun lint
Tested: bun typecheck
Tested: bun run build:desktop
2026-04-29 11:02:16 -07:00
Julius Marminge dbebc387dd Ignore stale WebSocket lifecycle events after reconnect (#2372) 2026-04-27 09:50:19 -07:00
Julius Marmingeandcodex 5cf83ffe8f fix(release): use configured node for smoke manifest merge (#2364)
Co-authored-by: codex <[email protected]>
2026-04-27 02:30:18 +00:00
t3-code[bot] ada410bccf chore(release): prepare v0.0.21 2026-04-23 18:05:15 +00:00
legs 00b5c3e1b3 Add task sidebar auto-open setting (#2314) 2026-04-23 13:59:08 -04:00
188df6da07 Fix Claude session cwd resume drift (#2292)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-23 13:29:54 -04:00
Pedro Silva 0d55a42840 fix(web): ignore stale runtime projection snapshots (#2301) 2026-04-23 15:52:02 +00:00
Thimo Sietsma 0ee302e24d fix(request-permission): add dynamic_tool_call to command request (#2311) 2026-04-23 15:42:35 +00:00
Julius Marminge d5b7690f95 Exclude subscribe RPCs from latency tracking (#2313) 2026-04-23 15:24:06 +00:00
8d1d699f88 Refactor provider model selections to option arrays (#2246)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
Co-authored-by: codex <[email protected]>
2026-04-23 09:35:40 -04:00
Raul Pereira da Silvaandmacroscopeapp[bot] b0b7b38da1 fix(server): detect localized Windows command errors (#2152)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-04-23 04:42:19 +00:00
Bas Milius fd3b96b487 Add IntelliJ project icon to the list of possible favicon paths (#1651) 2026-04-23 04:40:27 +00:00
Hauke Schnau aa2d385a62 fix(server): restore CODEX_HOME tilde expansion for Codex launches (#2255) 2026-04-23 00:37:58 -04:00
e25db3a572 Fix provider cache atomic write temp path collisions (#2291)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-23 00:33:16 -04:00
Heinz-GandHeinz Gericke b8305afa29 fix: increase Claude auth probe timeout to 10s (#2272)
Co-authored-by: Heinz Gericke <[email protected]>
2026-04-22 01:04:50 +00:00
Julius MarmingeandCursor Agent b7c89cf496 Refresh Codex protocol bindings to be75785504ff152fa6333e380a2d50642f42fba0 (#2276)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-21 15:30:54 -07:00
NoxireandJulius Marminge 3a1daa87ac Add close buttons to toasts (#2023)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-21 08:32:08 -07:00
Mike Olson 055897f0ea fix: enforce opencode >= 1.14.19 and reveal window on Wayland (#2262) 2026-04-21 08:15:41 -07:00
Adin Schmidt 40b3a80034 fix(server): trim OpenCode provider model names (#2252) 2026-04-21 02:45:56 +00:00
Adam Mansfield f6978db605 chore(turbo): pass through PATHEXT (#2184) 2026-04-19 23:35:37 -07:00
Mike Olson de05b0c94e fix(web): restore manual sort drag and keep per-group expand state (#2221) 2026-04-19 23:29:56 -07:00
CraigandJulius Marminge 6d1505c9fb fix: Change right panel sheet to be below title bar / action bar (#2224)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 23:25:39 -07:00
Julius MarmingeandClaude Opus 4.7 306ec4bb84 Refactor OpenCode lifecycle and structured output handling (#2218)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-04-19 22:56:44 -07:00
Julius Marmingeandcodex 3b98fe3548 effect-codex-app-server (#1942)
Co-authored-by: codex <[email protected]>
2026-04-19 21:46:40 -07:00
Ellie GummereandJulius Marminge 66c326b8c4 Redesign model picker with favorites and search (#2153)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 17:43:40 -07:00
8dbcf92a0d fix(server): prevent probeClaudeCapabilities from wasting API requests (#2192)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-20 00:13:20 +00:00
Abdul Azeez 37965da01d fix(server): handle OpenCode text response format in commit message g… (#2202) 2026-04-20 00:12:35 +00:00
Kyle Gottfried 57b59b5bf2 Devcontainer / IDE updates (#2208) 2026-04-19 17:07:12 -07:00
20f346d8ef Expand leading ~ in Codex home paths before exporting CODEX_HOME (#2210)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: = <=>
2026-04-20 00:06:19 +00:00
Efe Baran Durmaz c83bc5d48a fix(release): use v<semver> tag format for nightly releases (#2186) 2026-04-19 10:58:04 -07:00
Julius Marminge 9df3c64021 Use GitHub App token for release uploads (#2149) 2026-04-17 16:52:56 -07:00
Julius Marminge 8ac57f7944 Guard release workflow jobs on upstream success (#2147) 2026-04-17 16:40:43 -07:00
Julius Marminge 29cb917ac4 Guard release workflow jobs from upstream failures (#2146) 2026-04-17 16:34:19 -07:00
9c64f12ea0 Add ACP support with Cursor provider (#1355)
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-17 16:21:31 -07:00
Matt Van HornandMatt Van Horn 0f184c28b0 fix(web): use capture-phase keydown listener so CTRL+J toggles terminal from terminal focus on Windows (#2113) (#2142)
Co-authored-by: Matt Van Horn <[email protected]>
2026-04-17 23:07:04 +00:00
Julius Marminge a3b1df5224 Add Claude Opus 4.5 to built-in Claude models (#2143) 2026-04-17 16:02:41 -07:00
4e0c003e78 fix(web): allow deleting non-empty projects from the warning toast (#1264)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 15:05:56 -07:00
Utkarsh Patil 60387f67e9 fix: show restore defaults only on General settings (#1710) 2026-04-17 13:49:18 -07:00
ce94feeea1 feat: add opencode provider support (#1758)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-17 13:31:41 -07:00
Ariaj 39ca3ee858 fix(web): bypass xterm for global terminal shortcuts (#1580) 2026-04-17 13:11:04 -07:00
Julius Marminge 52a6067802 Throttle nightly release workflow to every 3 hours (#2134) 2026-04-17 11:39:20 -07:00
721b6b4c6f Preserve provider bindings when stopping sessions (#2125)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 11:27:12 -07:00
Julius Marminge 40009735ee Extract backend startup readiness coordination (#2133) 2026-04-17 11:09:26 -07:00
df9d34004f Modernize release workflow runners (#2129)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-17 16:23:02 +00:00
Julius Marminge f297e30e4c Clean up invalid pending approval projections (#2106) 2026-04-16 23:26:28 -07:00
Evan YuandJulius Marminge a7a44d0662 Fix Windows PATH hydration and repair (#1729)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-17 06:12:17 +00:00
Jono Kemball d8d329691a Show thread status in command palette (#2107) 2026-04-16 22:21:57 -07:00
Julius Marminge 54179c86b8 Update workflow to use ubuntu-24.04 runner (#2110) 2026-04-16 22:16:13 -07:00
Julius Marminge 8dba2d6484 Adopt Node-native TypeScript for desktop and server (#2098) 2026-04-16 22:14:35 -07:00
Nathan HarmonandJulius Marminge ed6b7fbf27 fix(server): honor gitignored files in workspace search (#2078)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 21:19:14 -07:00
Julius Marminge b991b9b9e6 Revert to Github Runner for Windows (#2103) 2026-04-16 20:35:56 -07:00
Julius Marminge 505db9f696 try out blacksmith for releases (#2101) 2026-04-16 20:12:09 -07:00
t3-code[bot] 2d87574e62 chore(release): prepare v0.0.20 2026-04-17 03:00:57 +00:00
Julius Marminge b2cca674df ci(release): install deps before finalize version bump (#2100) 2026-04-16 19:42:17 -07:00
Julius Marminge 549043863a fix: guard against missing sidebarProjectGroupingOverrides in client settings (#2099) 2026-04-17 02:36:39 +00:00
Julius Marminge b7df3dfca0 [codex] Fix Windows release manifest publishing (#2095) 2026-04-16 17:56:16 -07:00
Evan YuandJulius Marminge 6891c77d3e Build for Windows ARM (#2080)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 17:01:27 -07:00
m9d5m d90e15d1d7 fix(server): extend negative repository identity cache ttl (#2083) 2026-04-16 16:57:39 -07:00
e0117b271a Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:30:56 -07:00
188a40c315 feat: configurable project grouping (#2055)
Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-16 16:29:25 -07:00
Utkarsh Patil 7a08fcf2e8 fix(server): drop stale text generation options when resetting text-gen model selection (#2076) 2026-04-16 20:01:35 +00:00
Utkarsh Patil 19d47408a5 fix(web): prevent composer controls overlap on narrow windows (make plan sidebar responsive) (#1198) 2026-04-16 11:13:59 -07:00
Ibrahim ElkamaliandJulius Marminge 3e07f5a6a4 feat: add Claude Opus 4.7 to built-in models (#2072)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-16 11:11:59 -07:00
Marcus Grando d22c6f5280 fix: prevent user-input activities from leaking into pending approvals projection (#2051) 2026-04-16 05:09:29 +00:00
Marcus Grando 5e13f53571 fix: remove trailing newline from CLAUDE.md symlink (#2052) 2026-04-15 22:05:10 -07:00
f9580ff088 Default nightly desktop builds to the nightly update channel (#2049)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-15 21:31:24 -07:00
AndreiandJulius Marminge 5e1dd56d2c feat: add Launch Args setting for Claude provider (#1971)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 21:26:36 +00:00
legsandJulius Marminge 68061af042 Improve markdown file link UX (#1956)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 14:20:28 -07:00
Guilherme Vieira 28cb9db20b feat(web): add tooltip to composer file mention pill (#1944) 2026-04-15 13:29:13 -07:00
SakethandJulius Marminge 7968f278ee Fix terminal Cmd+Backspace on macOS (#2027)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-15 06:29:45 +00:00
44afe784a3 Add filesystem browse API and command palette project picker (#2024)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-14 23:26:05 -07:00
Julius Marmingeandcodex 9ff31f8c35 Fix nightly desktop product name (#2025)
Co-authored-by: codex <[email protected]>
2026-04-14 19:12:36 -07:00
409ff90a14 Nightly release channel (#2012)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-14 18:18:37 -07:00
0d280262f6 fix(claude): emit plan events for TodoWrite during input streaming (#1541)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-13 19:35:40 -07:00
Julius MarmingeandCursor Agent c9b07d665d Backfill projected shell summaries and stale approval cleanup (#2004)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-13 18:10:13 -07:00
2e42f3fdf6 Improve shell PATH hydration and fallback detection (#1799)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-13 16:31:43 -07:00
008ac5c3e5 Cache provider status and gate desktop startup (#1962)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-13 15:29:08 -07:00
Julius Marminge 9dcea68bce Refresh git status after branch rename and worktree setup (#2005) 2026-04-13 14:58:03 -07:00
Julius Marminge 5f7ec73a22 Fix new-thread draft reuse for worktree defaults (#2003) 2026-04-13 14:57:46 -07:00
Julius MarmingeandCursor Agent 569fea87a9 Warm sidebar thread detail subscriptions (#2001)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-13 13:55:20 -07:00
Julius Marminge 33dadb5aec Fix thread timeline autoscroll and simplify branch state (#2002) 2026-04-13 13:51:12 -07:00
Ashvin Nihalani d18e43b674 fix: lost provider session recovery (#1938) 2026-04-13 13:34:02 -07:00
Julius Marminge 6f699346e4 Use latest user message time for thread timestamps (#1996) 2026-04-13 13:20:10 -07:00
Julius Marminge f5ecca4480 Clear tracked RPCs on reconnect (#2000) 2026-04-13 20:16:08 +00:00
Utkarsh Patil cadd708646 feat: show full thread title in a tooltip when hovering sidebar thread names (#1994) 2026-04-13 12:26:41 -07:00
Ashvin NihalaniandJulius Marminge 5f7becf386 feat: Add Kiro editor support to open picker (#1974)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-13 19:16:00 +00:00
Ashvin Nihalani 9b29be916b docs: Document environment prep before local development (#1975) 2026-04-13 12:14:27 -07:00
Utkarsh Patil 047a0a697c fix: add pointer cursor to the permissions mode select trigger (#1997) 2026-04-13 12:13:44 -07:00
Julius Marmingeandcodex 77fcad3586 Prevent live thread branches from regressing to temp worktree names (#1995)
Co-authored-by: codex <[email protected]>
2026-04-13 19:04:56 +00:00
Julius Marminge 801b83e937 Allow empty server threads to bootstrap new worktrees (#1936) 2026-04-13 11:52:59 -07:00
Julius Marminge f2205bdc42 Pad composer model picker to prevent ring clipping (#1992) 2026-04-13 17:59:31 +00:00
Barry Michael Doyle 1bf048eb8b fix: avoid copy button overlapping long code blocks (#1985) 2026-04-13 09:59:22 -07:00
f7fa62aaf9 Add shell snapshot queries for orchestration state (#1973)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
Co-authored-by: codex <[email protected]>
2026-04-13 08:50:50 -07:00
Guilherme Vieira 57d7746a5d fix(web): replace turn strip overlay gradients with mask-image fade (#1949) 2026-04-13 01:11:34 -07:00
rowalth 850c912556 fix(desktop): increase backend readiness timeout from 10s to 30s (#1979) 2026-04-13 08:10:53 +00:00
Tarasandjulius dff8784aef window controls overlay (windows&linux) (#1969)
Co-authored-by: julius <[email protected]>
2026-04-13 07:21:40 +00:00
Julius MarmingeandCursor Agent 96c9306dbd Migrate chat scrolling and branch lists to LegendList (#1953)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-12 23:23:14 -07:00
Julius Marminge 94d13a2b75 Preserve live stream subscriptions across explicit reconnects (#1972) 2026-04-12 18:22:38 -07:00
7a008461fc fix: Align token usage metrics for both Claude and Codex (#1943)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-12 01:03:36 -07:00
Ashvin Nihalani f59ee36bf1 fix(web): allow concurrent browser tests to retry ports (#1951) 2026-04-12 07:46:44 +00:00
Ishan 2fce84a1d4 fix: quote editor launch args on Windows to support paths with spaces (#1805) 2026-04-12 00:41:11 -07:00
Julius Marmingeandcodex f9019cd63f Coalesce status refreshes by remote (#1940)
Co-authored-by: codex <[email protected]>
2026-04-11 18:51:04 -07:00
Adam Mansfield f9372a4c3d chore(desktop): separate dev AppUserModelID on Windows (#1934) 2026-04-12 00:18:59 +00:00
934037cb66 feat(web): add extensible command palette (#1103)
Co-authored-by: Hugo Blom <[email protected]>
Co-authored-by: eggfriedrice <[email protected]>
Co-authored-by: Jono Kemball <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-11 11:02:06 -07:00
Ishan 5467d11980 fix(web): prevent number-key shortcuts from hijacking input in focused editor (#1810) 2026-04-10 20:13:58 -07:00
Oliver Sargison 1f4a3f65bf Fix opening urls wrapped across lines in the terminal (#1913) 2026-04-10 19:30:25 -07:00
shivamandJulius Marminge 26cc1fffb3 Add assistant message copy action and harden related test/storage fallbacks (#1211)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-11 02:27:29 +00:00
Mike OlsonandJulius Marminge 97880e8870 fix(web): resolve logical-to-physical key mismatch in project drag reorder (#1904)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-10 19:25:43 -07:00
Julius MarmingeandCursor Agent b80e8476b8 Memoize derived thread reads (#1908)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-10 19:06:10 -07:00
Julius Marminge e0e01b4a54 Handle deleted git directories as non-repositories (#1907) 2026-04-10 18:31:24 -07:00
58e5f714b0 Add provider skill discovery (#1905)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-10 17:19:23 -07:00
Julius Marminge 4ae9de311b Stabilize auth session cookies per server mode (#1898) 2026-04-10 16:33:25 -07:00
shivam 5fa09fa2d9 [codex] fix composer footer compact layout (#1894) 2026-04-10 16:09:27 -07:00
Guilherme Vieira 12c3af7821 feat(desktop): add "Copy Image" to right-click context menu (#1052) 2026-04-10 15:02:07 -07:00
Julius Marminge e2316814da Fix worktree base branch updates for active draft (#1900) 2026-04-10 15:01:17 -07:00
Julius Marminge 678f827f0b Remove Claude subscription-based model adjustment (#1899) 2026-04-10 15:00:47 -07:00
t3-code[bot] a3dadf311e chore(release): prepare v0.0.17 2026-04-10 20:25:34 +00:00
Julius Marmingeandcodex e3004ae806 Harden secret store and resolve catalog overrides (#1891)
Co-authored-by: codex <[email protected]>
2026-04-10 13:09:39 -07:00
Ibrahim Elkamali 9385314d26 Persist changed-files expansion state per thread (#1858) 2026-04-10 10:41:41 -07:00
t3-code[bot] a3f292770e chore(release): prepare v0.0.16 2026-04-10 17:09:07 +00:00
Julius Marminge 2028d57e88 Fix server publish check for bin entrypoint (#1885) 2026-04-10 16:47:35 +00:00
3405a64dd8 bump effect to latest beta (#1866)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-10 01:51:31 -07:00
Julius Marminge 1cba2f64d3 Harden workspace git indexing against repo-configured fsmonitor execution (#1873) 2026-04-10 01:07:05 -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
Julius Marminge 24122b1762 Stabilize toast stacking offsets to prevent hover flicker
- derive toast indices and Y offsets from the filtered visible toasts
- pass frontmost height and per-toast layout vars to the viewport/item styles
- add unit tests for visible toast layout calculations and height normalization
2026-03-09 10:01:46 -07:00
Julius Marminge 081a6dacdb Remove fast-tier icons from model selection UI
- delete `shouldShowFastTierIcon` and its test
- remove Zap icon badges from slash model commands and provider model picker
- simplify related ChatView props and memo dependencies
2026-03-09 09:47:21 -07:00
Julius Marminge 9fdb45be1e Remove service tier setting from Codex flow and contracts
- Drop `serviceTier` from orchestration/provider contracts and server dispatch paths
- Remove service-tier app setting/UI and related resolver logic
- Keep fast badge behavior tied to explicit fast-mode boolean
2026-03-09 09:47:21 -07:00
Julius Marminge b946f00f1a Show Plan Ready status pill for settled plan threads
- add "Plan Ready" sidebar status when a plan-mode turn is settled with a proposed plan
- update sidebar logic tests to cover the new status and expanded thread inputs
2026-03-09 09:46:33 -07:00
Julius Marminge b030f69a83 Show Awaiting Input status in sidebar and extract status logic
- add `Sidebar.logic.ts` to centralize thread status pill resolution
- show `Awaiting Input` when plan mode is blocked on user responses
- add unit tests for unseen completion and status-priority behavior
- prevent plan collapse/expand clicks from triggering chat scroll anchoring
2026-03-09 09:46:33 -07:00
Julius Marminge b0e1b3368e Show toast when immediate project add fails
- Use a toast error for add-project failures during immediate folder browse
- Keep inline add-project error state for non-immediate flows
- Include `shouldBrowseForProjectImmediately` in callback dependencies
2026-03-09 09:31:39 -07:00
Julius Marminge ce7b24bfb1 Inline Electron project picker check in Sidebar
- Replace `shouldOpenProjectFolderPickerImmediately` with direct `isElectron` usage
- Remove obsolete `Sidebar.logic.ts` and its tests
2026-03-09 09:31:39 -07:00
Julius Marminge 5c286cab8b Open project folder picker immediately in Electron
- remove mobile-width gating from sidebar project picker behavior
- simplify picker logic/tests to depend only on Electron runtime
2026-03-09 09:31:39 -07:00
Julius Marminge 75ca0d4fa4 Open folder picker immediately on desktop Electron
- add `shouldOpenProjectFolderPickerImmediately` to centralize Sidebar behavior
- trigger folder browse directly when adding a project in desktop Electron
- keep manual path entry for mobile layouts and non-Electron, with tests for all cases
2026-03-09 09:31:39 -07:00
0x1f99d 8282b11fb5 refactor(contracts): remove unused OrchestrationPersistedEvent schema (#601) 2026-03-09 08:29:49 -07:00
github-actions[bot] 45744cc789 chore(release): prepare v0.0.9 2026-03-09 11:17:07 +00:00
Sai Shankar 4b6a0c433c fix(web): fix native scrollbar being intercepted by sidebar rail on windows and linux (#618)
the rail's 16px hit area at z-20 sits right where the native os scrollbar
lives when the sidebar is in offcanvas mode and collapsed. this causes clicks
and drags on the scrollbar to toggle the sidebar instead on windows and linux.

scoping pointer-events-none to [data-collapsible=offcanvas][data-state=collapsed]
fixes the interception without affecting icon mode where the rail needs to stay
clickable.
2026-03-09 04:03:13 -07:00
Theo Browne 304a14de7d Fix users who installed intel builds on arm macs (#641) 2026-03-09 04:01:23 -07:00
Theo Browne c585128bbe ARM ALWAYS FUCK YOU INTEL 2026-03-09 01:20:14 -07:00
Theo Browne acd92f9b06 include sourcemaps 2026-03-09 01:12:55 -07:00
0x1f99d 4088b7ac3c fix(desktop): use filesystem-friendly userData directory name (#607)
Electron derives the userData path from productName in package.json,
which produces directories with spaces and parentheses on all platforms
(e.g. ~/.config/T3 Code (Alpha) on Linux). This is hostile to shell
usage and violates Linux XDG naming conventions.

Override the userData path via app.setPath() before the ready event to
use a clean lowercase name (t3code). If the legacy directory already
exists it is used as-is so existing users keep their Chromium profile
data (localStorage, cookies, sessions, cache).

This follows the same pattern VS Code uses — keeping productName for
display purposes while explicitly setting the data directory path.

Closes #578
2026-03-08 22:02:15 -07:00
0x1f99d 8e8904a159 refactor(web): remove redundant double parse of diff route search params (#598)
`rawSearch` is already the output of `parseDiffRouteSearch` via the
`useSearch` select transform. The `useMemo` at line 760 re-parsed it
through the same function with an unsafe `as Record<string, unknown>`
cast, producing an identical result. Use `rawSearch` directly instead.
2026-03-08 21:55:09 -07:00
0x1f99d 16f3490aee fix(ci): handle draft PR conversions in pr-vouch (#611) 2026-03-08 21:53:26 -07:00
Jono Kemball 651084e8c0 fix: fix external link opening in desktop (#599)
fixes #434
2026-03-08 21:43:35 -07:00
Theo Browne 812bb99f5c Add Noojuno to vouched 2026-03-08 21:43:17 -07:00
Jason Laster 5bc79807ec Add an encyclopedia of common terms (#613) 2026-03-08 21:40:44 -07:00
github-actions[bot] 8fe21d7583 chore(release): prepare v0.0.8 2026-03-09 03:43:56 +00:00
0x1f99d 412331aa61 fix(web): add missing v7 key to legacy localStorage cleanup list (#594)
When the persisted state key was bumped from v7 to v8 in 689dda59,
the v7 key was not added to LEGACY_PERSISTED_STATE_KEYS. Users who
ran the app during the ~3-week v7 window retain a stale
`t3code:renderer-state:v7` entry in localStorage that is never
cleaned up.
2026-03-08 20:39:41 -07:00
Theo Browne cd1c3df89c Add PR vouch workflow with trust-status labels (#602)
* Add PR vouch workflow and trust-status labeling

- Add `.github/workflows/pr-vouch.yml` to label PRs as trusted, unvouched, or denounced
- Add `.github/VOUCHED.td` trust-list file for external contributors
- Document automatic `vouch:*` labels and contributor expectations in `CONTRIBUTING.md`

* Add vouch entries for trusted GitHub contributors

- Append 16 GitHub accounts to `.github/VOUCHED.td`
- Update trusted-voucher list used for PR labeling workflows
2026-03-08 20:36:37 -07:00
0x1f99d 3738373aa5 fix(server): use waitForPush in terminal event broadcast test to prevent flaky failure (#606)
The terminal RPC test used raw waitForMessage to receive the expected
terminal.event push, but a server.configUpdated push from the
keybindings file watcher can arrive first depending on OS timing.
Replace with the existing waitForPush helper that filters by channel.
2026-03-08 20:36:03 -07:00
Theo Browne 9b9006fed5 Fix release finalize lockfile refresh (#608)
* Add checkout and Node setup to release updater publish job

- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts

* Fix release finalize lockfile refresh
2026-03-08 20:30:01 -07:00
Theo Browne 42234b8f7c fix: plan mode ui overhaul (#596)
* new plan mode started

* review comments

* more fixes
2026-03-08 20:12:31 -07:00
Theo Browne 39f65703e7 Add checkout and Node setup to updater publish workflow job (#605)
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
2026-03-08 20:00:15 -07:00
(CJ) Chukwudi Nwobodo b7f954a904 Fix ChildProcess.spawn failing on Windows for .cmd shims (#495)
* fix(scripts): enable shell mode on Windows for .cmd shim resolution

On Windows, tools like `bun`, `npm`, `turbo`, and `bunx` are installed
as `.cmd` shims. Node's `child_process.spawn` cannot resolve these
without `shell: true`, causing `PlatformError: NotFound` on fresh
builds where there is no Turbo cache.

Add `shell: process.platform === "win32"` to all ChildProcess.make
calls in cli.ts, dev-runner.ts, and build-desktop-artifact.ts.

Closes #474

* docs: add comments explaining Windows shell spawn requirement

* docs: add shell spawn comments to remaining call sites
2026-03-08 18:58:25 -07:00
0x1f99d a20815ece6 fix(web): align sidebar logo with macOS traffic light buttons (#586)
Adjust the Electron sidebar header to properly center the T3 wordmark
with the native window controls. The logo was sitting ~2px too low and
~8px too close to the traffic lights.

- Reduce wordmark container top margin from mt-2 (8px) to mt-1.5 (6px)
- Increase Electron header left padding from 82px to 90px for proper
  traffic light clearance
- Match the desktop update button margin to stay aligned

Closes #564
2026-03-08 18:56:29 -07:00
Mubin Ansari 1c43bad705 Add delete option for project actions (#223)
Adds a delete button to the action edit dialog with a confirmation
alert. Fixes pingdotgg/t3code#208.
2026-03-08 18:51:55 -07:00
(CJ) Chukwudi Nwobodo 18b6590d2e feat(desktop): add spellcheck suggestions to context menu (#500)
Wire up Electron's context-menu event on webContents to surface
dictionary suggestions for misspelled words. Standard edit actions
(Cut, Copy, Paste, Select All) appear in all context menus.

Related to #473
2026-03-08 18:36:52 -07:00
Theo Browne d62ffa7560 pr changes pt2 2026-03-08 18:27:04 -07:00
0x1f99d 59e2944fb7 fix(web): add dismiss button to thread error banner (#588)
The thread error banner had no way to be dismissed. Users hitting
unrecoverable errors (e.g. missing gh CLI during PR creation) were
stuck with a persistent error banner and no way to clear it.

Add a dismiss (X) button to ThreadErrorBanner using the existing
AlertAction component, wired to clear the thread error via
setThreadError(id, null).

Closes #496
2026-03-08 18:24:56 -07:00
Theo Browne 17942787aa fix: settings in sidebar, better add project flow (#584)
* improvements

* sidebar ui pt2

* back flow

* fix back flow
2026-03-08 18:21:31 -07:00
Theo Browne 5815ba24e2 Add pull request template with contribution notice and review checklist (#582)
* Add PR template with contribution notice and review checklist

- Add `.github/pull_request_template.md`
- Set expectations that external PRs may not be reviewed or merged
- Require clear change rationale plus UI before/after media when applicable

* Add contribution policy notice and link detailed guidelines

- add CONTRIBUTING.md with clear expectations for external PRs
- update README to direct would-be contributors to CONTRIBUTING.md first
2026-03-08 18:20:05 -07:00
Noah Gregory 5de8e9d1ae fix: properly emit update metadata for intel macs (#446)
* fix: properly emit update metadata for intel macs

* refactor: fix broken parsing of quoted values
2026-03-08 18:03:18 -07:00
Aditya Vardhan Sharma 96e1e3db5e feat(marketing): add platform detection for download button (#558) 2026-03-08 17:45:40 -07:00
github-actions[bot] 5dd36bc5ad chore(release): prepare v0.0.5 2026-03-08 23:52:20 +00:00
Patrick BauerandPatrickBauer 6271b989bc fix(web): use wss:// when page is served over HTTPS (#391)
When T3 Code web mode is accessed via HTTPS (e.g. through a reverse proxy
or Tailscale Serve), the WebSocket connection must use wss:// instead of
ws://. Browsers block mixed content — an insecure ws:// connection
initiated from an HTTPS page.

Fix: derive the WebSocket protocol from window.location.protocol.

Co-authored-by: PatrickBauer <[email protected]>
2026-03-08 16:30:25 -07:00
James 57aa6bf16c fix: avoid duplicating streamed assistant completion text (#465) 2026-03-08 16:29:34 -07:00
Kainoa Newton 40a7f4b4b1 Rename Open PR action label to View PR (#467)
- Update GitActionsControl quick/menu action text for existing pull requests
- Align unavailable-state copy and tests with the new label
2026-03-08 16:27:39 -07:00
Kainoa Newton cba0f23a9e Remove extra dot from working indicator (#481)
- Drop the redundant static bullet before the working status text in `MessagesTimeline`
- Keep the animated dots indicator as the sole working-state visual cue
2026-03-08 16:27:03 -07:00
(CJ) Chukwudi Nwobodo a7ec0179fb Fix codex binary path setting having no effect (#493)
* refactor(contracts): export ProviderStartOptions schema

* feat(contracts): add providerOptions to ThreadTurnStartCommand

* feat(web): send codex binary/home path settings to server

* feat(server): thread providerOptions through to session startup

* fix(contracts): define ProviderStartOptions inline to avoid circular dep

The import from provider.ts caused a ReferenceError at runtime because
of module initialization order in the bundled output.

* fix(server): preserve providerOptions across runtime mode changes and session recovery

Runtime mode toggles and server restarts silently dropped the custom
codex binary/home path, falling back to the default binary. Cache
providerOptions per thread in ProviderCommandReactor and persist it in
the session binding's runtimePayload so recovery can restore it.

Closes #486
2026-03-08 15:55:49 -07:00
Jason Laster c97c6b7836 Enforce minimum Codex CLI version (≥0.37.0) before starting sessions (#404)
Add a pre-flight version check that runs `codex --version` and blocks
session startup with a clear upgrade message when the installed CLI is
below v0.37.0. The check runs both synchronously at session start
(codexAppServerManager) and during provider health probes
(ProviderHealth), so users get fast feedback in the UI.

Introduces `codexCliVersion.ts` with semver parsing, comparison, and
formatting helpers shared by both call sites.
2026-03-07 13:12:11 -08:00
github-actions[bot] 59b0527c38 chore(release): prepare v0.0.4-alpha.1 2026-03-07 12:19:51 +00:00
Theo Browne b74c7a79ab Handle prerelease tags in GitHub release publishing (#344)
* Handle prerelease tags when publishing GitHub releases

- Derive `is_prerelease` and `make_latest` from the version format in preflight
- Mark suffixed versions (for example `1.2.3-alpha.1`) as prereleases
- Keep only plain `X.Y.Z` releases marked as latest
- Document prerelease/latest behavior in `docs/release.md`

* Force desktop auto-updates to stable latest channel

- set Electron updater channel to `latest`
- disable prerelease and downgrade updates regardless of app version
2026-03-07 04:05:36 -08:00
github-actions[bot] f772720d8c chore(release): prepare v0.0.4 2026-03-07 10:38:31 +00:00
Hwanseo ChoiandCopilot 0763a35fbc Fix bun run dev:desktop from not terminating properly on SIGINT/SIGTERM/SIGHUP (#305)
* fix: handle turbo shutdown in dev runner

* refactor: rely on effect child process shutdown

* refactor: inline turbo shutdown timeout

* add back sigint sigterm sighup handling

* refactor: tighten turbo signal forwarding

* refactor: inline dev runner errors

* fix: use detached false instead of manual signal forwarding

Effect defaults to detached: true on non-Windows, putting turbo in a
new process group where terminal signals (Ctrl+C) never reach it.
Setting detached: false keeps turbo in the same group, eliminating
the need for ~130 lines of manual signal forwarding.

* Update scripts/dev-runner.ts

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
2026-03-07 02:20:17 -08:00
Guilherme Barros e1c33dcd33 Fix Fish shell PATH detection and clean up lint warnings (#323)
* Fix Fish shell PATH detection for Codex

* refactor(provider): resolve lint warnings in provider layers

* refactor(terminal): simplify thread lock release initialization

* test(git): simplify fetch release callback initialization
2026-03-07 02:14:30 -08:00
Ahmed R.andAhmed R 0a902790ca Fix crash when rendering code blocks with unsupported languages (#266 & #210) (#279)
The app crashed when displaying code blocks with language identifiers
not bundled in Shiki (e.g. "env" from .env file edits). The language
string was cast to SupportedLanguages without validation, causing
resolveLanguage to throw an unhandled error that killed the thread.

Three layers of defense added:
- getHighlighterPromise falls back to "text" when Shiki rejects
- codeToHtml call wrapped in try/catch with "text" fallback
- CodeHighlightErrorBoundary prevents component tree crashes

Closes #266

Co-authored-by: Ahmed R <[email protected]>
2026-03-07 02:12:54 -08:00
Theo Browne 0837c8b639 fix: everything AICodeKing reported (#320)
* Guard non-git projects and improve send and diff UX

- Skip checkpoint capture/revert and turn diff ingestion for non-git workspaces
- Normalize project workspace roots and return clearer request/error messages
- Show "No Git" state in chat/diff UI and enrich work log with commands/files
- Track send start time so working status shows elapsed duration consistently

* Format active working timer in concise h/m/s units

- add `formatWorkingTimer` for human-friendly durations in ChatView
- show active "Working for" time as `0s`, `1m 5s`, or `2h 3m` instead of ms

* more cleanup

* Fix active work timing and use temp git workspaces in tests

- derive active work start from unsettled turn state instead of always latest turn
- update chat view to use shared deriveActiveWorkStartedAt helper
- make server/ws tests create temporary workspace roots with .git for project creation
2026-03-07 02:06:55 -08:00
JoeEverest 5a90b6be9c #221: Fix missing list markers in chat markdown (#224)
Tailwind v4 Preflight resets list-style to none on ul/ol elements.
Restore disc/decimal markers and add nested list style variants
(circle, square, lower-alpha, lower-roman) for visual distinction.
2026-03-06 17:51:44 -08:00
github-actions[bot] 42675571c9 chore(release): prepare v0.0.3 2026-03-07 00:57:40 +00:00
Theo Browne e9f00f65ca Update README command and support link
- switch quickstart command from `npx t3@alpha` to `npx t3`
- fix wording in desktop app sentence
- replace "Discord link coming soon" with invite link
2026-03-06 16:56:10 -08:00
Julius Marminge 04b95e37c5 Change CLI package publish tag from alpha to latest 2026-03-06 16:27:42 -08:00
github-actions[bot] 5820e1b6ff chore(release): prepare v0.0.2 2026-03-07 00:17:26 +00:00
Theo Browne 8c904ffe34 Add production favicon set for marketing page (#196)
- add 16x16, 32x32, and Apple touch icon assets
- update `index.astro` head links to reference size-specific favicons
2026-03-06 15:53:32 -08:00
Theo Browne 9fa9cb4b31 Soften chat composer focus border color (#188)
- Reduce focused composer border intensity using `focus-within:border-ring/45`
- Keeps drag-over styling behavior unchanged
2026-03-06 15:53:12 -08:00
github-actions[bot] 24599aaeed chore(release): prepare v0.0.0-alpha.22 2026-03-06 23:08:37 +00:00
Theo Browne f403b23e9a Add Shift+Tab shortcut to toggle composer plan mode (#186)
- add Shift+Tab keyboard handling in composer to switch chat/plan modes
- refactor mode toggle into shared callback used by hotkey and button
- add browser test to verify toggling only works when composer is focused
2026-03-06 14:55:24 -08:00
Theo BrowneandClaude Opus 4.6 39c71a0394 Redesign marketing site with Astro (#187)
* marketing site

* redesign 1

* more

* Redesign marketing site: port to Astro, minimal dark homepage

Replace the React/Vite marketing site with a single static Astro page.
Dark theme matching the app aesthetic, featuring the production glossy
T3 icon, app screenshot, and a clean minimal layout.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Fix GitHub link to pingdotgg/t3code

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-06 14:45:41 -08:00
d249e628ee Stage production icons for desktop builds and publish (#168)
* Stage production icons for desktop builds and publish

- add shared brand asset paths and a Windows .ico asset
- stage Linux/Windows icons in desktop artifact builds
- override and restore publish favicon during server CLI publish

* 'blip'

* Fix PR review issues for publish icon staging

* Refactor brand assets and harden Windows desktop build setup

* Apply remaining server orchestration updates

* Fix production mac icon asset

Co-authored-by: Theo Browne <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-03-06 13:54:31 -08:00
Yash SinghandTheo Browne 40fcb6bdf8 fix: restrict spark to non-plus users & fast mode gpt5.4 (#180)
* fix: restrict spark to non-plus users & fast mode gpt5.4

* nit

* tests

* tests

---------

Co-authored-by: Theo Browne <[email protected]>
2026-03-06 13:48:37 -08:00
Julius Marminge d58ff5de26 Streamline composer behavior during pending approvals
- Treat pending approvals as a dedicated composer state
- Disable prompt input and hide command menu/image chips while approval is active
- Move approval decision buttons into footer actions and simplify the header panel
2026-03-06 09:03:16 -08:00
Julius Marmingeandcodex e28ad18106 Inline pending approvals in composer header
Co-authored-by: codex <[email protected]>
2026-03-06 09:03:16 -08:00
github-actions[bot] 525411101d chore(release): prepare v0.0.0-alpha.21 2026-03-06 08:08:47 +00:00
Julius Marminge 0f208447ed Prefer base HTML icon for .html files
- Override `.html` language mapping to use the generic HTML icon
- Add test coverage asserting `index.html` resolves to `file_type_html.svg`
2026-03-05 23:52:26 -08:00
Theo Browne 71e0573459 @alpha 2026-03-05 23:48:17 -08:00
Julius Marminge c63ea8d25b Use project cwd when opening draft threads without worktree
- Pass resolved `openInCwd` from ChatView into OpenInPicker
- Fall back to project `cwd` when draft thread has no `worktreePath`
- Add browser test covering Open action for draft-only snapshot
2026-03-05 23:44:26 -08:00
Julius Marminge b9e529e0b5 Preserve draft terminal state during snapshot cleanup
- add `collectActiveTerminalThreadIds` to keep non-deleted server threads plus local draft threads
- use helper in root event router before orphan terminal state removal
- add unit tests for retained and deleted thread behavior
2026-03-05 23:41:23 -08:00
Julius Marminge 0f702fcd62 server heartbeat 2026-03-05 23:40:49 -08:00
Julius Marmingeandcodex 13f2f9bc58 Fix ProviderService telemetry payload fields after rebase
Co-authored-by: codex <[email protected]>
2026-03-05 23:40:49 -08:00
Julius Marminge 91cf202177 Scope telemetry flush loop to service lifecycle
- Replace detached flush worker with scoped fiber in `AnalyticsService`
- Ensure periodic analytics flushing is tied to layer lifetime/cleanup
2026-03-05 23:40:49 -08:00
Julius Marminge d21a8d597b rm 2026-03-05 23:40:49 -08:00
Julius Marminge 14022f1d00 Refactor analytics flush test to use Effect NodeServices
- Wrap test in `it.layer(NodeServices.layer)` for Node service provisioning
- Replace manual temp dir setup/cleanup with scoped `FileSystem.makeTempDirectoryScoped`
- Keep multi-batch flush assertions while simplifying test runtime wiring
2026-03-05 23:40:49 -08:00
Julius Marminge 28c62f3efd Add test for analytics flush across multiple batches
- Verify `flush` drains 45 buffered events with batch size 20
- Assert three `/batch` POSTs are sent and event indexes 0-44 are delivered
2026-03-05 23:40:49 -08:00
Julius Marminge 268bb4bfa3 simplify layers 2026-03-05 23:40:49 -08:00
Julius Marminge 477b4f9d0e Wire telemetry in main and store anonymous ID in state dir
- move `AnalyticsServiceLayerLive` from CLI runtime setup into `main` server layer
- persist telemetry `anonymous-id` under configured `stateDir` instead of home directory
- add `FetchHttpClient.layer` to `main.test.ts` test layer wiring
2026-03-05 23:40:49 -08:00
Julius Marminge d5d88270f0 fallback 2026-03-05 23:40:49 -08:00
Julius Marminge 373725f96e record some machine info 2026-03-05 23:40:49 -08:00
Julius Marminge fcb1a50ee4 adjust 2026-03-05 23:40:49 -08:00
Julius Marminge ec3778bbf4 Add anonymous PostHog telemetry for provider lifecycle events
- introduce `AnalyticsService` with buffered PostHog batch flush
- add hashed telemetry identifier from Codex account id or anonymous local id
- record provider session/turn lifecycle events and flush on stop-all
- wire telemetry layer into server runtime and update tests with no-op analytics
2026-03-05 23:40:49 -08:00
Theo Browne 8c5b8d3b72 readme and shit 2026-03-05 23:07:59 -08:00
Julius Marminge 010ba70561 Fix plan follow-up mode switching and submission text
- Extract follow-up submission resolution into `resolvePlanFollowUpSubmission`
- Send implementation prompt in default mode when follow-up text is empty
- Keep composer mode toggle synced when starting same-thread implementation turns
- Add tests for follow-up submission behavior
2026-03-05 23:00:41 -08:00
Julius Marminge 6ee057e25b rm test 2026-03-05 23:00:41 -08:00
Julius Marminge 551aebc604 Add default collaboration mode preset for Codex turn starts
- Send `collaborationMode` for both `default` and `plan` interactions
- Add default-mode developer instructions and preserve plan-mode behavior
- Update server/web tests for default collaboration mode and model constant usage
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 9de85ea16e fix: preserve custom model picker selections
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 10dde452f9 fix: address core review findings
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 116c8c5e8e rm some aliases 2026-03-05 23:00:41 -08:00
Julius Marminge f8886e874d rm task lifecycle events from ui 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2435a9cd58 chore: move cursor acp probe artifacts to cursor stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 78d53062d1 refactor: move cursor provider surface out of core\n\nCo-authored-by: codex <[email protected]> 2026-03-05 23:00:41 -08:00
Julius Marminge 697d71d57d sync lock 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex d74b086aaf split: move Claude SDK and plan doc to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 6496aedc92 split: move Claude provider surface to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex e972fad300 model: move Claude catalogs out of core
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1bd4d6d953 contracts: move Claude schemas out of core
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge e9655d43d5 Show unavailable providers as coming-soon placeholders
- Keep Claude Code and Cursor in provider list as disabled options
- Remove unused Claude agent SDK dependency from server
- Delete stale plan-mode deep-dive doc
2026-03-05 23:00:41 -08:00
Julius Marminge f0a7ddaf80 sync lock 2026-03-05 23:00:41 -08:00
Julius Marminge ed6c12c709 rm tmp 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex a1b75fe17f test: move Claude coverage out of core PR
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2e5e75699e Remove Claude adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex be308beacc Remove Cursor adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 2589176c82 Add GPT-5.4 to Codex model options
- include `gpt-5.4` in Codex app model option coverage
- only keep truly custom Cursor models in the custom model option list
2026-03-05 23:00:41 -08:00
Julius Marminge adfd99bdec Plumb Codex model options through orchestration and composer
- Replace ad-hoc `effort` handling with provider `modelOptions` across decider/reactor/adapters
- Map Codex `reasoningEffort` and `fastMode` to turn/session params (`effort`, `serviceTier`)
- Persist runtime/interaction/model selections from composer and sync them before sending turns
- Move model normalization/helpers into `@t3tools/shared/model` with updated contracts/tests
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1683ee7b11 Fix post-rebase typecheck regressions
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge e6575c4149 Prune internal contract exports and remove checkpoint RPC schemas
- Stop exporting internal-only schema constants/types across contracts modules
- Remove unused provider checkpoint list/revert/diff RPC contract schemas
- Keep public contract surface focused on externally consumed types
2026-03-05 23:00:41 -08:00
Julius Marminge ae7283e021 style 2026-03-05 23:00:41 -08:00
Julius Marminge 640a2cca9f Persist proposed plans as first-class thread projection data
- Add `thread.proposed-plan-upserted` orchestration flow from ingestion through decider/projector
- Store proposed plans in a dedicated projection table and include them in snapshot queries
- Update provider runtime/web handling and tests to use proposed plans instead of assistant message wrappers
2026-03-05 23:00:41 -08:00
Julius Marminge 12edc3455c Add plan interaction mode and user-input request handling
- Wire Codex plan mode through turn start, including collaboration settings
- Track and answer pending `requestUserInput` prompts instead of auto-empty responses
- Persist/project thread `interactionMode` (schema, migration, queries) and update tests/contracts
2026-03-05 23:00:41 -08:00
Julius Marminge 26f631b638 Migrate provider runtime/session flow to thread-scoped IDs
- Replace provider session-id centric plumbing with thread-id based runtime handling across server orchestration and provider layers
- Update persistence repositories/migrations and contracts for threadless runtime semantics
- Refresh integration/unit tests and web session/store types to match the new runtime model
2026-03-05 23:00:41 -08:00
Julius Marminge 981cf40561 Improve session restart handling and server logging
- add structured lifecycle logs for Codex thread open/resume and provider session restarts
- introduce persistent server file logging layer and tighten WebSocket server startup/finalizer ordering
- preserve env-based boolean overrides in dev runner and stop forcing WS event logging in dev
- enrich provider session listing from persisted bindings and fix Claude rate-limit/task-id event mapping
- update orchestration and dev-runner tests for runtime-mode restart and env-flag behavior
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 689dda59e9 Persist thread runtime mode and handle mode-switch session restarts
- Add `thread.runtime-mode.set` -> `thread.runtime-mode-set` flow in decider/reactors/projectors
- Persist runtime mode on thread/session projections with new DB migrations
- Update provider and Codex integration tests to verify thread continuity across mode changes

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 0a67f9dd39 Clarify Cursor plan-mode semantics and ACP extension mapping
- Define Cursor operating mode as binary `default | plan`
- Document mapping for `cursor/ask_question`, `cursor/create_plan`, and `cursor/update_todos`
- Update capability and fallback guidance based on docs plus probe evidence
2026-03-05 23:00:41 -08:00
Julius Marminge df6bb188d4 Rewrite plan-mode deep dive as implementation blueprint
- Reframe doc into a provider-agnostic implementation plan for Codex, Claude, and Cursor
- Define canonical mode, plan, and structured user-input models plus capability-driven UI behavior
- Add concrete orchestration, adapter, frontend, and test work items for rollout
2026-03-05 23:00:41 -08:00
Julius Marminge 03053d9ee0 Add runtime mode tracking across provider orchestration pipeline
- extend provider and orchestration contracts for runtime mode-aware events
- persist runtime mode fields in projection thread session storage and migration 006
- update adapters, reactors, projections, websocket/web session logic, and tests
- add plan mode deep dive docs and probe artifacts for ACP behavior
2026-03-05 23:00:41 -08:00
Julius Marminge 9c4d7a83e2 Handle session.state.changed in provider runtime ingestion
- Map runtime session state transitions to orchestration session status
- Persist error reasons from `session.state.changed` error events
- Add coverage for waiting/error/stopped/ready transition handling
2026-03-05 23:00:41 -08:00
Julius Marminge 7425a3c4b3 Support provider custom models and fix runtime event mapping
- add per-provider custom model settings/options in web settings and chat picker
- preserve Codex request type on `serverRequest/resolved` events
- validate empty Cursor prompts before turn start and keep tool-call item types consistent
- add tests for new adapter and model-settings behavior
- add PR event review checklist document
2026-03-05 23:00:41 -08:00
Julius Marminge 344e04b623 Inject native event loggers into provider adapters
- allow Claude/Cursor adapters to accept an injected native event logger
- make native event writes effectful/non-blocking so logging cannot break message handling
- update adapter tests to assert native observability events via in-memory loggers
- fix runtime session ID conversion when resolving canonical event thread IDs
2026-03-05 23:00:41 -08:00
Julius Marminge 7b71e234e0 Normalize runtime events and tighten orchestration approval flow
- migrate fixtures/tests/adapters to canonical provider runtime event payloads
- route checkpoint capture off `turn.completed` only and drop legacy `checkpoint.captured` path
- stop faking approval resolution when provider reports stale/unknown pending requests
2026-03-05 23:00:41 -08:00
Julius Marminge 77f67d1766 Handle stale approval responses and cover Cursor resume IDs
- Catch provider approval response failures and emit `provider.approval.respond.failed`
- Auto-resolve approvals when provider reports unknown pending request IDs
- Add tests for Cursor ACP resume via `resumeCursor.acpSessionId` and legacy `sessionId`
2026-03-05 23:00:41 -08:00
Julius Marminge 1c2ed75937 Normalize approval request kinds and persist draft provider state
- map canonical approval request types to `requestKind` across ingestion and web pending approvals
- auto-approve Cursor permission requests when approval policy is `never`
- persist per-thread composer provider selection in draft store and use it in ChatView
- disable Cursor traits picker while model selection is locked
2026-03-05 23:00:41 -08:00
Julius Marminge 17e6cad479 Respect provider model-switch limits and canonical runtime events
- Add provider capability plumbing for `sessionModelSwitch` and use it in session/turn routing
- Keep Cursor sessions stable when in-session model switching is unsupported
- Ingest canonical runtime events (`content.delta`, `item.*`, `request.*`) with legacy-shape compatibility
2026-03-05 23:00:41 -08:00
Julius Marminge feff86638e Fix effort and provider handling in thread turn start
- Only include `effort` in start command when a value is selected
- Persist effort selection via composer draft state and hide picker when unavailable
- Add optional `provider` to `ClientThreadTurnStartCommand`
- Simplify thread model fallback selection in `ChatView`
2026-03-05 23:00:41 -08:00
Julius Marminge ad28eaa86f Scope composer draft reasoning effort to Codex options
- Switch draft store types to `CodexReasoningEffort`
- Validate and default effort using Codex-specific option/default constants
2026-03-05 23:00:41 -08:00
Julius Marminge d36bbc177d Unify provider runtime events and add Cursor adapter layer
- migrate Claude/Codex/registry adapters to canonical runtime event types and payload shapes
- add Cursor layer adapter plus tests and wire it through server layers
- update provider contracts/runtime schemas and related adapter tests
2026-03-05 23:00:41 -08:00
Julius Marminge aeddb57594 Scope reasoning effort defaults and options by provider
- Replace global reasoning constants with provider-scoped effort options/defaults
- Update ChatView to use Codex-specific reasoning effort types and default lookup
- Expand model contract tests for provider-specific reasoning effort behavior
2026-03-05 23:00:41 -08:00
Julius Marminge f2253269dd Introduce v2 provider runtime event schema and validation tests
- Restructure runtime events around a shared base plus typed payloads
- Add runtime-branded IDs and new event types (plan, item, request, user-input)
- Remove legacy canonical event names from docs and add schema decode/rejection tests
2026-03-05 23:00:41 -08:00
Julius Marminge d08cecf126 Document Cursor ACP mapping in canonical runtime event spec
- Add Cursor ACP raw source types to `RuntimeEventRaw.source`
- Define canonical mappings for ACP lifecycle, updates, permissions, and errors
- Expand cross-provider equivalence table to include Cursor ACP and renumber sections
2026-03-05 23:00:41 -08:00
Julius Marminge afad39d125 Revise Cursor provider plan for ACP JSON-RPC integration
- Switch plan from `agent -p` stream-json to `agent acp` JSON-RPC transport
- Document ACP session, permission, event-mapping, and interrupt/recovery behavior
- Update implementation phases, tests, and delivery checklist for ACP-first design
2026-03-05 23:00:41 -08:00
Julius Marminge f97916f371 Add Cursor ACP probe script and captured session logs
- add `scripts/cursor-acp-probe.mjs` to run ACP protocol probing scenarios
- update `package.json` scripts for probe execution
- include generated probe summaries/transcripts under `.tmp/acp-probe/`
2026-03-05 23:00:41 -08:00
Julius Marminge 86e204439e Add Cursor provider support across backend, contracts, and UI
- Accept `cursor` as a first-class provider in orchestration, persistence, and session directory flows
- Update model/provider inference and normalization to handle Cursor model aliases
- Revamp chat provider/model picker with Cursor-specific trait controls and add coverage in tests
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 04a931fc79 Add Cursor CLI stream event schemas and decoding tests
- define `CursorAdapter` service contract and Cursor stream-json schema types
- add `CursorCliStreamEvent` decoding tests for system/thinking/tool/result/retry events
- add implementation plan for Cursor provider integration

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 75354bbd96 Track runtime event sequence and order thread activities by sequence
- add per-session `sessionSequence` on provider runtime events and persist activity `sequence`
- migrate `projection_thread_activities` with nullable `sequence` column + index
- sort server/web activity projections by sequence fallback to timestamp/id
- allow provider sessions/turns to start before a real threadId is emitted
2026-03-05 23:00:41 -08:00
Julius Marminge 6a10e97a97 Align Claude permissions and provider-specific reasoning effort
- Default Claude sessions to bypass permissions when approval policy is `never`, while preserving explicit `permissionMode`
- Hide/send reasoning effort only for providers that support it in ChatView
- Add coverage for Claude permission-mode derivation and precedence, and update runtime event model docs
2026-03-05 23:00:41 -08:00
Julius Marminge 1542b00db2 Stabilize Claude turn event ordering and native event logging
- Preserve active turn state when `session.started`/`thread.started` arrive mid-turn
- Emit `message.delta` from assistant text when stream deltas are missing, then complete the message
- Add Claude native SDK NDJSON observability logging and wire its log path in server layers
- Expand ingestion/adapter tests to cover mid-turn lifecycle and delta fallback behavior
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex f79f8bac80 Fix ProviderService sendTurn recovery expectation after rebase
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 92f1a4aa3c Ignore stale resume cursors and Claude placeholder thread IDs
- Do not pass `resumeCursor` when restarting a session after changing providers
- Treat synthetic Claude thread IDs (`claude-thread-*`) as unscoped during runtime ingestion
- Add tests covering provider-switch restart behavior and Claude turn lifecycle acceptance
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 11f929c397 Align orchestration integration tests with latestTurn metadata
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 0616338911 Fix Claude resume cursor to only persist valid session UUIDs
- Stop synthesizing `resume` from generated thread IDs
- Persist resume session ID from query messages when available
- Validate resume/sessionId values as UUIDs before reuse
- Add tests for valid UUID resume passthrough and no synthesized resume
2026-03-05 23:00:41 -08:00
Julius Marminge 58427d565d Refactor ClaudeCodeAdapter session flow and stream handling
- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable`
- Use `Ref` for shared session context in tool approval callbacks
- Simplify timestamp/ID generation and close sessions via queue shutdown
2026-03-05 23:00:41 -08:00
Julius Marminge 9b3dbada17 Integrate Claude agent SDK into server provider adapter
- add `@anthropic-ai/claude-agent-sdk` dependency for `apps/server`
- replace placeholder Claude adapter with live session/query/event handling
- add comprehensive adapter tests for runtime events, approvals, resume, rollback, and model overrides
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 4797f99cf8 Include all provider models in /model slash command
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 50f35351a2 Fix Claude model fallback in web store sync
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex c7460bde16 Update Claude model catalog to latest 4.6/4.5 gen
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2c110e8ce2 Show provider logos in composer model trigger
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 5707a6ee1d Use grouped provider/model select in chat composer
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 291411a45e Inline Claude adapter behavior into live layer
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 87abc22f39 unnecessary catch 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 441582dbb8 Use typed errors for unavailable Claude runtime path
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1b1ede92ba Make Claude runtime boundary Effect-native
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 4ec7ae33c5 Add Claude integration coverage across orchestration flows
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 317fcc659b Add Claude checkpoint and revert reactor coverage
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex ff7e084a33 Enable Claude provider selection in chat composer
Add provider-aware model options and include provider in turn-start dispatch.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex c590beb4e3 Support provider-aware session selection in reactor
Add restart semantics when requested provider changes and cover with tests.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex e9ced44ac6 Wire Claude adapter into registry and server provider layer
Add provider-service routing coverage for explicit claudeCode sessions.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 802cd127d1 Add Claude Code adapter live layer with error mapping tests
- introduce `ClaudeCodeAdapter` service and live layer wiring
- map runtime/session/request failures into provider adapter error types
- add coverage for validation, session-not-found mapping, lifecycle forwarding, and event passthrough
2026-03-05 23:00:41 -08:00
Julius Marminge 931c56b2d0 revised plan 2026-03-05 23:00:41 -08:00
Julius Marminge 484662b2d4 redo contracts a bit 2026-03-05 23:00:41 -08:00
Julius Marminge 2cd04f08c1 Add provider-specific model resolution and defaults
- Add per-provider model options, defaults, and slug aliases
- Add provider-aware model normalization/resolution helpers
- Preserve Codex-only constants/functions for backward compatibility
- Extend tests to cover Claude aliases and provider-specific fallback behavior
2026-03-05 23:00:41 -08:00
Theo Browne 4916dad78e license 2026-03-05 22:58:18 -08:00
github-actions[bot] d5c97faac5 chore(release): prepare v0.0.0-alpha.20 2026-03-06 00:31:16 +00:00
Julius Marminge 531b12e192 repo too 2026-03-05 16:15:34 -08:00
Julius Marminge b293b083fc add missing bin to published package 2026-03-05 16:15:34 -08:00
Julius Marminge b297e20f4e Fix release target commit and gate version bump steps
- Set `target_commitish` from preflight ref when creating GitHub releases
- Track whether package versions changed and expose it via step output
- Run format, lockfile refresh, and bump commit only when changes exist
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 44be7f3ac3 Run oxfmt on package.json files after version bump
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius MarmingeandClaude Opus 4.6 ea5a100a74 Defer release commit+tag to finalize job
Move the version bump commit and tag creation out of the preflight job
into a new finalize job that runs only after build, publish, and release
all succeed. This prevents orphaned version commits and tags on main
when downstream jobs fail.

- Preflight: validate version, lint/test only — no commit/tag/push
- Release: softprops/action-gh-release creates tag for workflow_dispatch
- Finalize: bump package.json versions, refresh lockfile, commit to main

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-05 16:15:34 -08:00
Julius Marminge 6841fa17d4 Scope changed-files tree PR to relevant files
- revert unrelated server-side attachment/image changes from this branch\n- keep changed-files tree UX fixes (icons, directory behavior, whitespace-safe paths, stat visibility)\n\nCo-authored-by: codex <[email protected]>
2026-03-05 15:56:40 -08:00
Julius Marminge 5c03804bac Improve changed-files tree UX and harden attachment path handling
- Compact single-directory chains in turn diff trees and preserve branch points
- Add per-turn expand/collapse-all controls and themed VS Code file icons in ChatView
- Centralize attachment route prefix stripping and tighten image/extension normalization helpers
2026-03-05 15:56:40 -08:00
Julius Marminge d6ed393255 Render changed files as expandable tree with aggregated diff stats
- Replace flat changed-files chips in ChatView with a nested, expandable tree
- Extract diff tree/stat logic into turnDiffTree utilities
- Add unit tests for stat aggregation, nesting, and Windows path normalization
2026-03-05 15:56:40 -08:00
Julius Marminge 2d9139767a Refine sidebar thread actions and list preview
- Move "New thread" action to each project header with hover icon + shortcut tooltip
- Limit thread lists to 6 items by default with per-project Show more/Show less controls
- Remove the global sidebar-level new thread button
2026-03-05 15:16:10 -08:00
Julius Marminge 95fcc89074 Prevent toast content overflow in collapsed stack
- Use the larger of shared stack height and per-toast height to avoid clipping
- Make toast content columns flexible with `min-w-0` and `break-words`
- Keep action buttons from shrinking so long text wraps instead of overflowing
2026-03-05 14:43:19 -08:00
Julius Marminge eb59853596 Add Copy Thread ID action to thread context menu
- Add a `Copy Thread ID` item to the thread context menu in the sidebar
- Copy the selected thread ID via Clipboard API
- Show success/error toasts based on copy result
2026-03-05 14:42:02 -08:00
Julius Marminge a2682de421 Use mention adjacency helper in composer onChange
- replace Lexical-node cursor adjacency check with text/cursor helper
- prevent `@query` typing from being treated as mention-pill adjacent
- add regression test for non-pill `@pac` input
2026-03-05 11:04:40 -08:00
Julius Marminge 325c0a3687 Limit composer mention arrow jumps to adjacent mention boundaries
- Only intercept left/right arrow keys when cursor is directly next to a mention
- Prevent default arrow behavior only for those mention-boundary moves
- Add `isCollapsedCursorAdjacentToMention` logic with coverage for left/right adjacency cases
2026-03-05 11:04:40 -08:00
Julius Marminge 7c7fcf46c2 Handle system timeline messages with assistant height rules
- Route `system` messages through assistant height estimation
- Keep user attachment height logic scoped to user messages
- Add regression test for system-message sizing behavior
2026-03-05 10:20:34 -08:00
Julius Marminge 0c39733cbf Expand ChatView height parity tests across responsive viewports
- Add viewport matrix coverage for long text and attachment row-height parity
- Reuse a mount/measure test harness to validate resize behavior in one session
- Ensure production CSS and viewport sizing are applied before measurements
2026-03-05 10:20:34 -08:00
Julius Marminge a76413594e Fix chat attachment height on narrow timeline resizes
- recompute timeline width from the root element on ResizeObserver updates
- rerun width effect when message/working state changes
- reduce minimum user chars per line for narrow layouts and add regression test
2026-03-05 10:20:34 -08:00
Julius Marminge 1100d5a6f7 Use vi.waitFor in ChatView browser measurement helpers
- Replace manual timeout polling loops with `vi.waitFor` in test helpers
- Improve reliability of locating and measuring virtualized user rows in attachment-height tests
2026-03-05 10:20:34 -08:00
Julius Marminge 9abf967700 Use vitest-browser-react in ChatView browser tests
- replace manual `createRoot` mounting with `render`/`unmount` from vitest-browser-react
- add `vitest-browser-react` to web devDependencies and lockfile
2026-03-05 10:20:34 -08:00
Julius Marminge cc83094bc6 add back title 2026-03-05 10:20:34 -08:00
Julius Marminge f5bdc138f6 Stabilize ChatView attachment height browser test with MSW
- Run ChatView browser tests through the real app router/store stack
- Add MSW worker setup and mocked WS/attachment responses for full-app rendering
- Extract shared `getRouter` setup and add a timeline root data hook for reliable measurement
2026-03-05 10:20:34 -08:00
Julius Marminge 2d8ca48175 Use real TanStack router in ChatView browser tests
- Replace mocked router hooks with a memory router + RouterProvider
- Render ChatView through a test route to exercise attachment height layout in realistic routing context
2026-03-05 10:20:34 -08:00
Julius Marminge 4ca4a1f99c Migrate ChatView height browser tests to Vitest + Playwright
- Replace Playwright e2e timeline-height test setup with Vitest browser config
- Add `ChatView.browser.tsx` parity tests for text wrapping and attachment height estimation
- Add row data attributes in `ChatView` to support in-browser measurement targeting
2026-03-05 10:20:34 -08:00
Julius Marminge 5470801c4a Add Playwright timeline height parity tests to CI
- add browser E2E tests validating timeline height estimator against rendered DOM
- configure Playwright test runner and scripts in `apps/web`
- run browser tests in CI with Playwright browser caching and install step
2026-03-05 10:20:34 -08:00
Julius Marminge 2ad2d3e6f5 Make chat timeline height estimates width-aware and test them
- extract `estimateTimelineMessageHeight` into `timelineHeight.ts`
- account for timeline width and explicit newlines when estimating wrapped lines
- re-measure virtualized rows on width changes to fix attachment/message height sizing
- add Vitest coverage for assistant/user wrapping and attachment row height rules
2026-03-05 10:20:34 -08:00
Julius MarmingeandClaude Opus 4.6 b175d6b2a3 Fix CLI publish using stale package.json version
The publish_cli job was checking out the default ref instead of the
preflight commit, so it published with the pre-bump version. Add the
correct ref to checkout and a --app-version flag as a safety override.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 10:20:07 -08:00
github-actions[bot]andcodex c5c12aa738 chore(release): prepare v0.0.0-alpha.18
Co-authored-by: codex <[email protected]>
2026-03-04 18:01:45 +00:00
Julius Marminge 7241400edd Add electron-updater and refresh lockfile package versions
- add `electron-updater` dependency for `apps/desktop`
- bump workspace package versions from `0.0.0-alpha.13` to `0.0.0-alpha.16`
- update transitive lockfile entries accordingly
2026-03-04 09:58:22 -08:00
Julius Marminge 310fd0b187 Wait for child process tree shutdown before forcing kill
- add `childTreeGracePeriodMs` constant for shutdown timing
- await grace period after `TERM` before sending `KILL` to avoid dev process leaks
2026-03-04 09:58:22 -08:00
Julius Marminge db94743220 Remove electronmon-specific cleanup from desktop dev script
- drop `electronmon` from desktop dependencies
- stop killing stale processes by matching electronmon hook paths
- keep cleanup scoped to `--t3code-dev-root` processes only
2026-03-04 09:58:22 -08:00
Julius Marminge 07aaf37fd4 Prevent desktop dev Electron process leaks during restarts
- replace `electronmon` with explicit Electron spawn/stop lifecycle management
- debounce file-watch restarts for main/preload/server build outputs
- add stale-process cleanup and forced child-tree shutdown fallback
2026-03-04 09:58:22 -08:00
Julius MarmingeandClaude Opus 4.6 65a808808f Fix electron-updater auth for private GitHub repos
Use setFeedURL with private: true when a GitHub token is provided so
electron-updater queries the GitHub API instead of the public Atom feed
which rejects Bearer auth headers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 00:27:47 -08:00
github-actions[bot]andcodex cca1aa1588 chore(release): prepare v0.0.0-alpha.16
Co-authored-by: codex <[email protected]>
2026-03-04 07:21:44 +00:00
Julius Marminge c9d4b773c9 Remove target arg from electron-builder invocation
- stop passing `options.target` to the electron-builder CLI
- keep platform flag, arch, and `--publish never` unchanged
2026-03-03 23:13:53 -08:00
github-actions[bot]andcodex e23f3102f4 chore(release): prepare v0.0.0-alpha.15
Co-authored-by: codex <[email protected]>
2026-03-04 06:35:27 +00:00
Julius Marminge ec89587c37 Refactor desktop update flow with retryable action results
- Extract desktop updater state transitions into `updateMachine` reducers with tests
- Extend update IPC/contracts to return `{accepted, completed, state}` for download/install actions
- Add web sidebar update-button logic for retryable download/install errors and clearer tooltips
2026-03-03 22:31:45 -08:00
Julius Marminge 32d89806d7 Extract desktop update state helpers and improve update UX
- Add `updateState` helpers for auto-update eligibility reasons and progress throttling
- Show a user-facing dialog when manual update checks are unavailable
- Ensure manual update checks can open a window when none exist
- Add tests for disable-reason logic and 10% download progress bucketing
2026-03-03 22:31:45 -08:00
Julius Marminge 2fd4e06b34 Allow update checks when status is available
- Stop skipping `checkForUpdates` when updater state is `available`
- Continue skipping only while an update is downloading or already downloaded
2026-03-03 22:31:45 -08:00
Julius Marminge 3cffdce1c1 Harden desktop auto-update timer lifecycle
- track and clear startup + poll update timers through one cleanup path
- prevent update checks from starting while the app is quitting
- reset startup timer before scheduling to avoid duplicate checks
2026-03-03 22:31:45 -08:00
Cursor AgentandJulius Marminge 6d2f4f4cdf fix: remove misleading log and redundant guard in handleCheckForUpdatesMenuClick
The guard for status === 'downloaded' logged 'skipping automatic install'
but the function only checks for updates, never installs. The guard was
also redundant since checkForUpdates() already returns early for
'downloaded', 'downloading', and 'available' statuses with correct
log messages.

Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-03 22:31:45 -08:00
Julius Marminge 865d7bd684 Guard update install while app is quitting
- Prevent update install from running when shutdown is already in progress
- Ignore install IPC calls once `isQuitting` is set to avoid duplicate install attempts
2026-03-03 22:31:45 -08:00
Julius Marminge 392d63231c Harden desktop update flow and prevent duplicate update actions
- Skip redundant update checks while update is available/downloading/downloaded
- Wait for backend shutdown before `quitAndInstall` and improve updater error/progress handling
- Prevent sidebar update button clicks during download while preserving tooltip interactivity
2026-03-03 22:31:45 -08:00
Julius Marminge 7559f5ad70 style 2026-03-03 22:31:45 -08:00
Julius Marminge 605e8143e0 Prevent redundant checks during desktop update download
- Skip desktop auto-update checks while an update is downloading or already downloaded
- Subscribe to update-state events before initial fetch in sidebar to avoid stale state races
2026-03-03 22:31:45 -08:00
Julius Marmingeandcodex 5b056cd337 fix: remove duplicate catalog resolver after rebase
Co-authored-by: codex <[email protected]>
2026-03-03 22:31:45 -08:00
Julius Marminge 6c350489b1 Add desktop auto-update flow and publish updater assets
- wire `electron-updater` into desktop main/preload IPC and shared contracts
- add sidebar update action for download/install state in Electron UI
- update release workflow/build script to include `latest*.yml` and `*.blockmap` assets
2026-03-03 22:31:45 -08:00
julius 2ae63f4aa2 Fix shell: true side effects on Windows (orphaned processes, swallowed ENOENT)
Add tree-kill via taskkill /T /F in processRunner and codexAppServerManager so timeout enforcement and session stop properly terminate the entire process tree instead of just the cmd.exe wrapper. Detect Windows command not found (exit 9009) in normalizeExitError. Pre-validate editor commands with isCommandAvailable in open.ts before spawning. Fix ProviderHealth test import and dev-runner test path assertion for Windows.

Made-with: Cursor
2026-03-03 21:03:16 -08:00
julius 3d0233e3b0 fmt test 2026-03-03 21:03:16 -08:00
julius 64f2c3a465 effectify 2026-03-03 21:03:16 -08:00
julius 0a12333448 Fix Codex process spawning and health checks on Windows
- Run Codex-related child processes with `shell` on Windows for reliable command execution
- Switch provider auth probe to `codex login status` and update health-check expectations
- Use Node PTY on Windows instead of Bun PTY in server runtime setup
2026-03-03 21:03:16 -08:00
Julius Marminge 9db54c9b19 Handle Codex auth JSON arrays and flag missing auth markers
- Parse nested/array JSON auth status output from `codex auth status --json`
- Return `unauthenticated` when JSON contains `authenticated: false`
- Return warning when JSON is parseable but lacks an auth marker
2026-03-03 21:03:16 -08:00
julius 34430e3514 windows dev 2026-03-03 21:03:16 -08:00
Julius Marminge 99e44f2c23 Add Codex provider health status to server config and chat banner
- add startup ProviderHealth service/layer to probe Codex install and auth state
- extend server contracts and WS payloads to include provider statuses
- show non-ready provider warnings in ChatView and cover with server/web tests
2026-03-03 21:03:16 -08:00
github-actions[bot]andcodex 7a0f2d9b30 chore(release): prepare v0.0.0-alpha.14
Co-authored-by: codex <[email protected]>
2026-03-04 03:03:52 +00:00
Julius Marminge 4bf310f7ca disable provenacnes while repo is private 2026-03-03 18:59:11 -08:00
github-actions[bot]andcodex 8b9fbe701d chore(release): prepare v0.0.0-alpha.13
Co-authored-by: codex <[email protected]>
2026-03-04 02:25:54 +00:00
Julius Marminge 0c5be023e4 fix test 2026-03-03 18:22:29 -08:00
Julius Marminge 86e87a8789 better lables 2026-03-03 18:22:29 -08:00
Julius Marminge 404e78a506 logging 2026-03-03 18:22:29 -08:00
Julius Marminge 73563c7c25 Add Vitest to root devDependencies
- add `vitest` via catalog in root `package.json`
- update `bun.lock` to include the new workspace dependency
2026-03-03 18:22:29 -08:00
Julius Marminge 326595b148 Add Vitest to web app and remove unused composer/env props
- add `vitest` to `apps/web` devDependencies and lockfile
- remove unused `envMode` prop from `BranchToolbar` usage and signature
- drop unused composer command input ref in `ChatView`
2026-03-03 18:22:29 -08:00
Julius Marminge 41a8468b08 Add effect dependency to desktop app package
- include `effect` in `apps/desktop` runtime dependencies
- update `bun.lock` to reflect the new dependency
2026-03-03 18:22:29 -08:00
Julius Marminge ced2ecb6ba install node 2026-03-03 18:22:29 -08:00
Julius Marminge 2d746b3a7e rm 2026-03-03 18:22:29 -08:00
Julius Marminge e6ac39de75 Migrate dev-runner to typed Effect CLI config and env fallbacks
- Replace string-based env override plumbing with typed config/flag parsing
- Split server/web offset resolution from explicit port/dev-url overrides
- Refactor and expand dev-runner tests around offset/env behavior
- Add `vitest` as a contracts dev dependency for test execution
2026-03-03 18:22:29 -08:00
Julius Marminge b76a0a6c91 Migrate dev runner to TypeScript and share NetService
- Replace `scripts/dev-runner.mjs` with typed `scripts/dev-runner.ts` in a new `@t3tools/scripts` workspace
- Move networking helpers into `@t3tools/shared/Net` and reuse them in server and desktop
- Add shared NetService tests and align workspace deps to `catalog:` versions
2026-03-03 18:22:29 -08:00
Julius Marminge 9fdec3c2c8 Fix npm publish command process invocation
- Pass command and args directly to `ChildProcess.make` in the publish CLI
- Remove fragile template-literal invocation to ensure command runs reliably
2026-03-03 10:55:23 -08:00
Julius Marminge 760fe643e8 helper 2026-03-03 10:01:18 -08:00
Julius Marminge 93af851dc5 type 2026-03-03 10:01:18 -08:00
Julius Marminge fabb3e0734 Extract branch selector and refresh branches on menu open
- Move branch combobox logic into `BranchToolbarBranchSelector` to simplify `BranchToolbar`
- Re-fetch git branches when opening the selector so options are current
- Preserve draft env mode correctly when switching between main and worktree branches
2026-03-03 10:01:18 -08:00
Julius Marminge 9ca9a862a5 Fix branch selector default and loading behavior in worktree mode
- Default new worktree branch selection to the current checked-out branch when unset
- Extract branch value resolution into shared logic with tests
- Stabilize virtualized branch list scroll/measurement to avoid loading glitches
2026-03-03 10:01:18 -08:00
github-actions[bot]andcodex 827dc9ff9f chore(release): prepare v0.0.0-alpha.12
Co-authored-by: codex <[email protected]>
2026-03-03 18:01:00 +00:00
Julius Marminge 09b32ac9dd Extract slash model option filtering into shared app settings helper
- add `getSlashModelOptions` to centralize `/model` suggestion filtering
- include custom saved model slugs in slash-command suggestions
- update ChatView to consume shared helper and add focused tests
2026-03-03 09:31:54 -08:00
Julius Marminge 253684e280 kewl 2026-03-03 09:18:08 -08:00
Julius Marminge f6d40ce841 log? 2026-03-03 09:12:28 -08:00
github-actions[bot]andcodex 36fb1bb7e4 chore(release): prepare v0.0.0-alpha.11
Co-authored-by: codex <[email protected]>
2026-03-03 17:09:58 +00:00
Julius Marminge 4a82c1608f fix pub 2026-03-03 09:06:05 -08:00
github-actions[bot]andcodex 3efb3da007 chore(release): prepare v0.0.0-alpha.10
Co-authored-by: codex <[email protected]>
2026-03-03 08:33:23 +00:00
Julius Marminge 11606fd9c6 cli for pub 2026-03-03 00:30:15 -08:00
github-actions[bot]andcodex a935db07ef chore(release): prepare v0.0.0-alpha.9
Co-authored-by: codex <[email protected]>
2026-03-03 07:36:01 +00:00
Julius Marminge 98860a9549 ignore scripts on publish 2026-03-02 23:33:14 -08:00
github-actions[bot]andcodex 7688742b2a chore(release): prepare v0.0.0-alpha.8
Co-authored-by: codex <[email protected]>
2026-03-03 07:02:39 +00:00
Julius Marminge b2efe4f83c cwd 2026-03-02 22:56:37 -08:00
github-actions[bot]andcodex f934b435fa chore(release): prepare v0.0.0-alpha.7
Co-authored-by: codex <[email protected]>
2026-03-03 06:46:02 +00:00
Julius Marminge 3c121585da publish cli? 2026-03-02 22:42:21 -08:00
github-actions[bot]andcodex 40acfbd2df chore(release): prepare v0.0.0-alpha.6
Co-authored-by: codex <[email protected]>
2026-03-03 06:01:37 +00:00
Julius Marminge 0af61bf6ba verbose 2026-03-02 21:58:36 -08:00
github-actions[bot]andcodex 7b2968f2ff chore(release): prepare v0.0.0-alpha.5
Co-authored-by: codex <[email protected]>
2026-03-03 05:55:00 +00:00
Julius Marminge a1c7b98f98 fix build script 2026-03-02 20:59:56 -08:00
Julius Marmingeandcodex 99ea16a969 Restore Open PR CTA for commit_push with existing PR
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex ebe44d03a5 Revert git action button logic toward main behavior
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex dcd2d50768 Keep non-default quick action on full PR flow
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex f11764c517 Fix PR CTAs and quick action after push
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 77c81b7468 Restore Open PR toast action after PR creation
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 7a5ccd3310 Fix toast follow-up actions to avoid re-branching
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex e4df6fcf8e Scope default-branch PR confirmation to full stack
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex b2be7f4e4f Address PR feedback on git workflows
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 94beb21a43 Skip commit progress stages when create-PR runs push-only
- pass `forcePushOnlyProgress` for the create-PR action
- add logic test to ensure only push and PR stages are shown
2026-03-02 20:46:05 -08:00
Julius Marminge 30e05538b7 Limit default-branch confirmation to direct push
- Stop showing default-branch confirmation for `commit_push_pr`
- Keep confirmation only for direct `commit_push` actions
- Update logic test to match the new behavior
2026-03-02 20:46:05 -08:00
Julius Marminge c884947ea8 Scope branch checkout effect during auto branch creation
- Wrap checkout in `Effect.scoped` when creating a new feature branch
- Align branch switch lifecycle with scoped effect handling
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 61289a152d Fix duplicated branch logic and feature-branch dialog on push-only
Deduplicate feature/ prefix logic in resolveAutoFeatureBranchName by
delegating to sanitizeFeatureBranchName. Skip the default-branch
confirmation dialog when there are no uncommitted changes (push-only),
since runFeatureBranchStep requires dirty worktree. Add merge-base
assertions to feature branch tests.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 906550f9af Merge feature-branch checkout into atomic runStackedAction
Consolidate the fragile 3-RPC flow (suggestCommitAndBranch → createBranch +
checkout → runStackedAction) into a single server-side operation triggered by
`runStackedAction({ featureBranch: true })`. The server now generates the
branch name via AI, deduplicates it, creates + checks out the branch, then
runs the normal commit/push/PR pipeline atomically.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge c2aaa89b57 Document contracts and shared package responsibilities
- Clarify that `packages/contracts` is schema-only with no runtime logic
- Add `packages/shared` as the home for shared runtime utilities and subpath exports
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 dde48e9414 Move branch sanitization from contracts to new shared package
Create @t3tools/shared with explicit subpath exports (no barrel) for
shared utility logic. Move sanitizeBranchFragment and
sanitizeFeatureBranchName to @t3tools/shared/git, keeping contracts
focused on schemas.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 b1608f41ad Extract branch sanitization to shared contracts module
Move sanitizeBranchFragment and sanitizeFeatureBranchName from three
duplicate definitions (CodexTextGeneration, GitManager, GitActionsControl)
into packages/contracts/src/git.ts. Remove the redundant double-sanitization
of branch names between the TextGeneration and GitManager layers —
CodexTextGeneration now owns sanitization of model output while GitManager
trusts the result and only sanitizes the custom commit message path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 78d89e3d35 non-dupicate 2026-03-02 20:46:05 -08:00
Julius Marminge 1309495218 optional 2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.5 c34a4c69e5 Add AI-generated semantic branch naming for git commits
Replace date-based auto feature branch names (feature/stacked-YYYYMMDD)
with semantically meaningful names derived from AI-generated commit
messages. The text generation prompt now returns a branch field alongside
subject and body, and a new suggestCommitAndBranch endpoint exposes this
to the web client for the default-branch checkout flow.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 2f6cac0cf0 no forwardref needed 2026-03-02 20:31:39 -08:00
Julius Marminge 5c26df3a4f Virtualize branch picker list and forward ComboboxList ref
- Add virtualized rendering and filtered item handling in `BranchToolbar`
- Memoize branch-derived data and sync highlight scrolling for large branch sets
- Convert `ComboboxList` to `forwardRef` to support virtualizer scroll targeting
2026-03-02 20:31:39 -08:00
Julius Marminge 302323a64b Fix Windows command detection and branch checkout error flow
- tighten win32 command availability checks for PATHEXT and PATH delimiter handling
- add server tests for Windows executable resolution edge cases
- stop branch/create flows after checkout/create failures to avoid stale optimistic UI
- remove OpenInPicker side effect that persisted last editor on render
2026-03-02 18:53:21 -08:00
Julius Marminge b981fad920 Sync thread metadata after worktree branch rename
- Dispatch `thread.meta.update` with the renamed branch after `git.renameBranch`
- Remove pre-rename active-branch status check and related skip path
- Update reactor tests to assert branch metadata moves to generated branch
2026-03-02 18:53:21 -08:00
Julius Marminge 8a2f2a5c2b Gate embedded commit hash lookup to packaged desktop builds
- Prefer `T3CODE_COMMIT_HASH` when set
- Return `null` for unpackaged desktop runs instead of reading embedded metadata
2026-03-02 18:53:21 -08:00
Julius Marminge e319735ed1 Refactor commit hash resolution in About panel
- Remove git command execution for commit hash retrieval
- Simplify commit hash resolution to use environment variable and embedded hash only
- Clean up unused code in IPC handler registration
2026-03-02 18:53:21 -08:00
Julius Marminge e7790490f1 Show desktop commit hash in About panel
- embed `t3codeCommitHash` into staged desktop package metadata during builds
- resolve commit hash from env/package/git and display it as About panel version
2026-03-02 18:53:21 -08:00
Julius Marminge a638978b75 Refactor branch toolbar actions to use transition-based git ops
- replace React Query mutations with direct git API calls wrapped in `useTransition`
- show toast errors for branch create/checkout failures and keep optimistic branch updates
- disable branch controls during pending actions and refresh branches when opening menu
2026-03-02 18:53:21 -08:00
Julius Marminge 4a08686e74 Add Zed editor support across open-in flow
- add `zed` to shared editor contracts and Open In picker
- add Zed icon and wire launch resolution tests on macOS
- wrap branch optimistic updates in `startTransition` to avoid sync warnings
2026-03-02 18:53:21 -08:00
Julius Marminge b3de2bd926 Expose available editors and gate Open In options
- Add server-side command detection and return `availableEditors` in server config
- Update Chat header Open In picker to show only installed editors and handle empty state
- Extend server/web tests and contracts for `availableEditors`; remove unused branch-sync logic
2026-03-02 18:53:21 -08:00
Julius Marminge b81ec02984 Show optimistic active branch during checkout and branch creation
- use `useOptimistic` in `BranchToolbar` to update active branch immediately
- keep optimistic branch in sync on success and roll back on mutation errors
2026-03-02 18:53:21 -08:00
Julius Marminge de61c0c42b Guard worktree branch rename and fix branch toolbar state
- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
2026-03-02 18:53:21 -08:00
Julius Marminge ecb4a1efa4 Add VS Code open support and stabilize chat autoscroll
- add VS Code to editor contracts and picker UI
- use `code --goto` for line/column targets in open resolution
- refine chat scroll intent handling to avoid unwanted stick-to-bottom jumps
2026-03-02 16:06:17 -08:00
Julius Marminge 1b0093a483 fmt 2026-03-02 16:03:11 -08:00
Julius Marminge 06fc364ee1 Scope git checkout effects and bump Effect/Node dependencies
- run `gitCheckout` via `Effect.scoped` to satisfy new `Scope` requirement
- update `GitCore.checkoutBranch` service signature to include `Scope.Scope`
- upgrade Effect catalog refs and `@types/node` to latest pinned versions
2026-03-02 16:03:11 -08:00
Julius Marminge 094859bbc7 Allow chat composer to shrink within constrained layouts
- Replace composer form `min-w-fit` with `min-w-0` in `ChatView`
- Prevent overflow and improve responsiveness in narrow containers
2026-03-02 15:42:05 -08:00
Julius MarmingeandClaude Opus 4.6 5e78386cdc Improve composer menu highlighting and suppress triggers near mentions
Adds visual active-item highlighting to the command menu, suppresses
trigger detection when the cursor is adjacent to a mention pill, and
resets transient UI state on thread change.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 14:16:08 -08:00
Julius Marminge c378afeff8 Fix composer mention cursor handling and trigger detection
- Treat mention pills as atomic cursor units in Lexical selection math
- Add left/right arrow + selection normalization behavior around mention nodes
- Expand collapsed mention cursor before trigger detection so @path menu closes correctly
- Update mention pill rendering for non-editable, non-selectable chips and theme-aware icons
- Add tests for collapsed-to-expanded cursor mapping and trigger behavior
2026-03-02 14:16:08 -08:00
Julius MarmingeandClaude Opus 4.5 bf7002209e Add Lexical-based composer editor with file mention pills
Introduce ComposerPromptEditor component using Lexical for rich text
editing with @-mention support for files. Includes mention detection
utilities and tests.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 14:16:08 -08:00
Julius MarmingeandClaude Opus 4.6 a3aa4bd189 Fix destructive menu icon showing app logo on non-macOS
getDestructiveMenuIcon fell back to resolveIconPath("png") on
Windows/Linux which resolved to the T3 Code app icon, not a trash
icon. Restrict the icon to macOS where createFromNamedImage("trash")
provides the correct system icon.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 5a0006f7ef Guard all commitRename cleanup paths against concurrent renames
All exit paths in commitRename now use a thread-guarded finishRename
helper that only clears renamingThreadId when it still matches the
original threadId. Prevents a stale onBlur from cancelling a newly
started rename on a different thread.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 9e2e73c070 Import ContextMenuItem from contracts in desktop app
Remove the duplicate DesktopContextMenuItem interface and use the
shared ContextMenuItem type from @t3tools/contracts instead.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 c530e5d50f Guard commitRename cleanup against concurrent renames
After the async dispatch, only clear renamingThreadId if it still
matches the thread being renamed, preventing a second rename's
input from being cleared by the first's completion.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 674720c6cd Use shared ContextMenuItem type from contracts
Re-export ContextMenuItem and replace the inlined
{ id: T; label: string; destructive?: boolean } definitions in
wsNativeApi, contextMenuFallback, and the test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 58c9e4b96d Make ContextMenuItem interface module-private
Only used internally within ipc.ts for DesktopBridge and NativeApi
type signatures, so no need to export it.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 feb286379c Stop keydown propagation on rename input
Prevents Space from triggering the parent SidebarMenuSubButton's
navigation handler while typing in the inline rename input.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 cefe641586 Remove unused prompt dialog infrastructure
The inline rename replaces the prompt dialog entirely, so remove the
promptDialog.ts file, IPC channels, bridge methods, and related tests.
Context menu improvements (destructive, position) are kept.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 664451c296 Replace prompt dialog with inline rename in sidebar
Thread rename now uses an inline input directly in the sidebar row
instead of opening a separate Electron BrowserWindow or browser
window.prompt. Enter commits, Escape cancels, blur saves.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 fd4ff8ca46 Restore lost useMemo calls in ChatView and fix threadActivities referential stability
Revert bare function calls / IIFEs back to useMemo for: modelOptions,
workLogEntries, latestTurnHasToolActivity, pendingApprovals, timelineEntries,
revertTurnCountByUserMessageId, completionSummary, and
completionDividerBeforeEntryId.

Add EMPTY_ACTIVITIES module-level constant so the ?? [] fallback doesn't
create a new array reference every render, which was defeating memoization.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 1bcfbdf287 rm 2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.6 4e45c1a6ab Fix store selector consistency, memoize timelineMessages, and suppress false-positive lint warnings
- Hoist removeOrphanedTerminalStates to a top-level selector in EventRouter
  for consistency with other store selectors
- Convert timelineMessages IIFE to useMemo with proper deps
- Suppress no-map-spread in ChatView (spread is conditional, immutability required)
- Suppress exhaustive-deps for autoFocus in TerminalViewport (mount-time only)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Cursor AgentandJulius Marminge 32fe80d164 Fix terminal focus on toggle, clean up orphaned terminal state, and revoke optimistic message blob URLs on unmount
- Add setTerminalFocusRequestId call when terminal opens via toggle so the
  terminal panel receives focus automatically
- Call clearTerminalState when deleting threads in the Sidebar and add
  removeOrphanedTerminalStates to prune stale entries after read model sync
- Track optimisticUserMessages via ref and revoke their blob URLs in the
  unmount cleanup effect to prevent memory leaks

Co-authored-by: Julius Marminge <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marmingeandmacroscopeapp[bot] 6e93d42023 Update apps/web/src/routes/__root.tsx
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.6 6f50867aa1 Improve store referential stability and fix reactive terminal state
- Deep clone DEFAULT_THREAD_TERMINAL_STATE in createDefaultThreadTerminalState
- Remove imperative getTerminalState from terminal store; export
  selectThreadTerminalState for reactive selectors instead
- Fix Sidebar terminal activity indicator not updating (was using
  non-reactive getter)
- Add no-op bailouts to app store transitions (updateThread,
  markThreadVisited, markThreadUnread, setError, setThreadBranch,
  setProjectExpanded, setRuntimeMode) to prevent unnecessary re-renders
- Use createDefaultThreadTerminalState in clearTerminalState to avoid
  storing frozen reference

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 4fca60469d Reset ChatView per thread and simplify derived state handling
- Mount `ChatView` with `key={threadId}` to fully reset UI state on thread switch
- Replace effect-driven local state with direct derived values and cleaner cleanup paths
- Simplify async command/script flows and minor context memo handling in sidebar/ui components
2026-03-02 13:13:19 -08:00
Julius Marminge afcd824ae9 fix(web): resolve post-rebase selector/store regressions
Remove duplicate selector declarations introduced during rebase and restore the streamlined AppStore shape so Zustand selector usage remains consistent.
Restore Sidebar cleanup semantics and pure store test assertions so lint/typecheck stay green after rebasing.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge f84f279738 Refactor Zustand store usage to granular selectors
- Replace combined `useStore` state/dispatch wrapper with direct selector/action hooks across chat UI components
- Inline and harden terminal state transitions inside `terminalStateStore` and remove `threadTerminalState`
- Add `terminalStateStore` action tests covering defaults, splits, groups, activity, and close/reset behavior
2026-03-02 13:13:19 -08:00
Julius Marminge 246624ad3c Refactor terminal state store to use granular thread selectors
- Replace `getTerminalState` reads with `selectThreadTerminalState` in ChatView and Sidebar
- Split terminal reducer into pure thread terminal operations used by the Zustand store
- Drop persisted default thread entries and add tests for the new operation helpers
2026-03-02 13:13:19 -08:00
Julius Marminge 410444aead Remove useStore selector compatibility shim
Drop the temporary selector overload from useStore and migrate the remaining selector call sites to the unified { state, dispatch } API so the store surface stays single-path.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge 7522d3bde3 refactor(web): remove reducer pattern, use Zustand + pure functions
- Main store: replace useReducer with Zustand; pure state transition
  functions (syncServerReadModel, markThreadVisited, setError, etc.)
  called via store methods. Persist via subscribe.
- Terminal store: single store keyed by threadId; replace
  dispatchTerminalAction with direct methods (setTerminalOpen,
  setTerminalHeight, splitTerminal, newTerminal, setActiveTerminal,
  closeTerminal, setTerminalActivity). Pure reduceThreadTerminalState
  used internally.
- Update all consumers to call dispatch.method(...) and terminal
  store methods. Fix store tests to use markThreadUnread pure fn.
- Fix Fragment import in store.ts; fix unused get param for lint.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge ed26b84177 Remove draftThreadTerminalState re-exports; use threadTerminalState directly
- Delete draftThreadTerminalState.ts (was only re-exporting shared module)
- Replace draftThreadTerminalState.test.ts with threadTerminalState.test.ts
  using createDefaultThreadTerminalState and reduceThreadTerminalState
- Draft threads are first-class: same helpers and types as persisted threads

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge ad4d12cf94 Unify draft and persisted thread terminal flow
- Add shared threadTerminalState.ts: ThreadTerminalState type, default state,
  normalize helpers, and single reduceThreadTerminalState() used by both flows
- Refactor store.ts to use shared terminal reducer and helpers; terminal
  actions map to reduceThreadTerminalState(threadTerminalSlice(thread), action)
- Make draftThreadTerminalState.ts re-export shared module (same shape/actions)
- Add terminalState to composer draft store: getDraftThreadTerminalState,
  setDraftThreadTerminalAction, clearDraftThreadTerminalState; draft thread
  shape matches Thread terminal slice
- ChatView: move draft terminal from useState into composer draft store; use
  same actions for draft and persisted; hydrate then clear draft terminal
  when reconciling server state

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.5 f6fd760e4e Enable terminals for local draft threads
Adds local terminal state management for draft threads before they're
promoted to server threads. Terminal operations (open, split, create,
close, activate, resize) now work on draft threads and hydrate into
the server thread state when the draft is promoted.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 506a5260dc Refactor store actions to use direct Zustand state updaters
- Remove Action union/reducer dispatch path in `store.ts`
- Extract per-action state transition helpers and apply via `setAppState`
- Update `store.test.ts` to validate behavior through `useStore` actions
2026-03-02 13:13:19 -08:00
Julius Marminge d4c90d696d Simplify Zustand selectors by removing memoized callbacks
- Replace `useCallback`-wrapped `useStore` selectors with inline selectors
- Apply across chat, diff, branch toolbar, and chat thread route components
2026-03-02 13:13:19 -08:00
Julius Marminge be4d26a1b3 Refactor web store usage to granular selectors
- Replace broad `useStore` state reads with targeted selector/action hooks across chat, diff, sidebar, and routing views
- Remove dispatch-style calls in favor of direct store actions to reduce unnecessary rerenders
- Improve chat UI interactions (composer menu navigation, image preview buttons, modal click targets)
- Add local `react-doctor` agent skill docs under `apps/web/.agents/react-doctor`
2026-03-02 13:13:19 -08:00
Julius Marminge 5c09614319 refactor: remove redundant workLogCount stick-to-bottom effect
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.

Made-with: Cursor
2026-03-02 10:19:22 -08:00
Julius Marminge 4c846332c5 fix: align handoff preview URLs with image attachment index
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.

Made-with: Cursor
2026-03-02 10:19:22 -08:00
Julius Marminge a3a0cbf0f8 Stabilize chat scroll restoration across thread switches
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
2026-03-02 10:19:22 -08:00
Julius Marminge 2c7101092a Set default cursor on sidebar session rows
- Add `cursor-default` to sidebar row classes in `Sidebar.tsx`
- Keeps list items from showing a pointer cursor while preserving hover/active styles
2026-03-02 00:06:23 -08:00
Julius Marminge 9f068356a4 Allow non-required dev ports to exceed max in offset search
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
2026-03-01 23:53:31 -08:00
Julius Marminge f239c90628 Auto-select next available dev ports per mode
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
2026-03-01 23:53:31 -08:00
Julius Marminge 991dd05e72 Use forkScoped for background upstream refresh
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
2026-03-01 23:24:22 -08:00
Julius Marminge 96bf54e293 Serve fallback project favicon when no icon file is found
- return an inline SVG favicon instead of 404 when project/icon files are missing
- add route test coverage for fallback response status and MIME type
2026-03-01 23:18:45 -08:00
Julius Marminge 5ca9b54d66 Preserve $defs in Codex output schema and refine sidebar header
- include JSON Schema `$defs` when writing Codex output schema files
- tighten sidebar wordmark sizing and spacing in Electron/web layouts
2026-03-01 23:11:44 -08:00
Julius Marminge 4ab5fca4ca Preserve draft env mode across thread and branch context updates
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 69a4fa8215 Show branch toolbar for local draft threads
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 9e04bad0a5 Run setup script after promoting local draft threads
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
2026-03-01 22:36:35 -08:00
Julius Marminge a574d9c936 Cover runtime undefined draft thread options in store test
- Build options object with runtime `undefined` values via cast
- Pass object into `setProjectDraftThreadId` to verify handling path
2026-03-01 22:36:35 -08:00
Julius Marminge 005e13089a Preserve draft branch/worktree when update options are undefined
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
2026-03-01 22:36:35 -08:00
Julius Marminge d9cce6402a Clean up orphaned composer drafts and harden draft checks
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 508872e04b Preserve explicit DEFAULT_MODEL draft overrides
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex aced302b63 Address PR review feedback for draft model/error/persistence handling
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 0b8dfee17b Simplify composer draft persistence and remove debug instrumentation
- Remove ChatView draft persistence debug logging and storage size plumbing
- Drop in-memory persisted draft cache; use JSON storage directly
- Reconcile attachment IDs from localStorage and streamline image hydration
2026-03-01 22:36:35 -08:00
Julius Marminge 6ab246676e Refactor draft thread lookups and cache persisted draft state
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
2026-03-01 22:36:35 -08:00
Julius Marminge 122c94a24a Defer thread creation until first message send
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
2026-03-01 22:36:35 -08:00
Julius Marminge b59c6d6ab1 Unify project draft thread state in composer draft store
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
2026-03-01 22:36:35 -08:00
Julius Marminge c9995995a4 Preserve draft metadata and dedupe composer image retries
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
2026-03-01 22:36:35 -08:00
Julius Marminge 545a9193e2 Persist per-thread composer drafts and reuse project draft threads
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
2026-03-01 22:36:35 -08:00
Julius Marminge fa0205cba3 Run checks before release commit and set desktop buildVersion
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
2026-03-01 20:33:00 -08:00
github-actions[bot]andcodex 8a20bd7f54 chore(release): prepare v0.0.0-alpha.4
Co-authored-by: codex <[email protected]>
2026-03-02 04:23:28 +00:00
Julius Marmingeandcodex 10660f376c fix(server): remove duplicate branchExists declaration
Co-authored-by: codex <[email protected]>
2026-03-01 20:19:39 -08:00
Julius Marmingeandcodex ae235f7155 feat(ci): add release workflow_dispatch version tagging
Co-authored-by: codex <[email protected]>
2026-03-01 20:13:24 -08:00
Julius Marminge a356cd0d0f Remove unused attachment route path helpers
- delete route-to-path conversion helpers from `attachmentPaths`
- remove unused `attachmentRoutePath` export and route prefix import
2026-03-01 20:06:21 -08:00
Julius Marminge 58b932ffb8 Normalize attachment thread segments to lowercase
- Lowercase sanitized thread segments when creating attachment IDs
- Add coverage for mixed-case thread IDs in attachment store and projection pipeline tests
2026-03-01 20:06:21 -08:00
Julius Marminge d58af33fba Fix attachment cleanup to match exact thread segments
- Parse thread segments from attachment IDs using a UUID-aware pattern
- Prevent revert/delete cleanup from removing files belonging to similarly prefixed threads
- Add tests for prefix-collision cases in attachment store and projection pipeline
2026-03-01 20:06:21 -08:00
Julius Marminge a56418f8bc Reuse attachment thread segment sanitizer in projection pipeline
- export and reuse `toSafeThreadAttachmentSegment` from `attachmentStore`
- align projection attachment path logic with store-safe thread IDs
- update projection pipeline tests to cover thread IDs with spaces
2026-03-01 20:06:21 -08:00
Julius Marminge 596e1590df Read stdin before validating required image flag in codex test stub
- Move stdin capture earlier in fake codex script setup
- Ensure stdin-based assertions remain available even when image validation fails
2026-03-01 20:06:21 -08:00
Julius Marminge 70c9147c7f Harden attachment ID resolution and missing-file handling
- Sanitize thread-derived attachment ID segments to safe, bounded tokens
- Resolve attachment IDs only when a matching file exists on disk
- Return 404 (not 400) for missing attachment IDs in the attachment route
- Add attachmentStore tests for ID sanitization and extension-based path lookup
2026-03-01 20:06:21 -08:00
Julius Marminge c0054cb56f Switch image attachments to persisted ID-based paths
- add attachment store helpers for IDs, route paths, and file resolution
- stop projection pipeline from mutating/storing data URLs; keep attachment metadata unchanged
- update Codex send/branch generation flows and tests to resolve images via attachment IDs
2026-03-01 20:06:21 -08:00
Julius Marmingeandcodex 41734dfbbf fix: address PR review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:21 -08:00
Julius Marminge 8f42d34db9 Inject test ServerConfig across orchestration and git layers
- add `ServerConfig.layerTest(cwd, stateDir)` to standardize test wiring
- require `ServerConfig` in `CodexTextGeneration` attachment path resolution
- update orchestration/projection tests and harness to use managed runtimes with explicit config
2026-03-01 20:06:21 -08:00
Julius Marminge 70857ce299 Handle parameterized base64 image data URLs
- accept `data:image/...;...;base64,...` headers while still rejecting invalid formats
- add `imageMime` tests for mime params, non-base64 URLs, and missing mime types
- fork branch-generation prompt effect at call site in `ProviderCommandReactor`
2026-03-01 20:06:21 -08:00
Julius Marminge 5e0ec38383 Use Effect Schema to decode Codex structured outputs
- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions
- Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString`
- Map `SchemaError` to `TextGenerationError` for invalid Codex responses
- Update `ProviderCommandReactor` test mock typing for `generateBranchName`
2026-03-01 20:06:21 -08:00
Julius Marminge 913d0409f6 Handle branch-name generation failures as typed errors
- Make branch-name generation return a required string instead of nullable output
- Propagate invalid Codex branch payloads as `TextGenerationError` instead of silently falling back
- Update provider command reactor to catch generation failures, log warnings, and skip rename safely
2026-03-01 20:06:21 -08:00
Julius Marminge ac0e720de1 fine there 2026-03-01 20:06:21 -08:00
Julius Marminge 5144d32b77 nit 2026-03-01 20:06:21 -08:00
Julius Marminge 128cc21516 data uri for app server 2026-03-01 20:06:21 -08:00
Julius Marminge 215ff36362 nit 2026-03-01 20:06:21 -08:00
Julius Marminge 505b4d0bc3 Resolve persisted attachment paths across server pipelines
- add shared attachment path normalization and resolution helpers
- reuse persisted image files for turn start and branch name generation
- cover persisted attachment flow in text generation and reactor tests
2026-03-01 20:06:21 -08:00
Julius Marminge 343c0a9472 Generate temporary worktree branch names from UUID tokens
- Remove message/time hashing for temporary branch names in `ChatView`
- Use an 8-char UUID token while preserving backend-detected suffix format
2026-03-01 20:06:21 -08:00
Julius Marminge 82681606d0 Remove git.renameBranch RPC and harden branch rename args
- remove `git.renameBranch` from WS/contracts/native API surface and update server/web tests
- use `git branch -m -- ...` in GitCore to safely separate branch rename arguments
2026-03-01 20:06:21 -08:00
Julius Marminge c91b79b6e2 Scope upstream refresh in checkout effect lifecycle
- Replace fire-and-forget `Effect.runPromise` call with `Effect.forkScoped`
- Keep checkout responsive while tying upstream refresh to scoped effect management
2026-03-01 20:06:21 -08:00
Julius Marminge 5e55aa387f Move worktree branch auto-rename into provider turn reactor
- Generate and rename temporary `t3code/*` worktree branches on first user turn in `ProviderCommandReactor`
- Remove websocket/client branch-generation RPCs and related contract/API surface
- Update Codex text-generation prompt to include attachment metadata only when attachments exist, with expanded tests
2026-03-01 20:06:21 -08:00
Julius Marminge a21095bc9a Add AI-generated worktree branch naming and safe branch rename
- add `git.generateBranchName`, `git.generateAndRenameBranch`, and `git.renameBranch` websocket flows
- pass image attachments into Codex branch-name generation and normalize/sanitize results
- add GitCore branch rename with collision-safe numeric suffixing
- extract shared image MIME/data-url helpers and expand server/web tests for new behavior
2026-03-01 20:06:21 -08:00
Julius Marmingeandcodex ba03241df3 fix: address latest git action review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex a8059dc2c0 fix: reuse git action toast after feature-branch checkout
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex be873bca3e fix: widen default-branch action dialog
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Cursor AgentandJulius Marminge e8bde958f1 Fix: reset hasUpstream, aheadCount, behindCount in statusOverride after branch checkout
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 95f21c1099 fix: make default-branch confirmation copy action-aware
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 8cd92150b1 test: use dynamic default branch in remote-base-ahead case
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex d0ab35931e fix: resolve no-upstream base from origin tracking branches
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 882684a80c fix: keep toast CTA git actions on the active feature branch
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 96efd1cef0 fix: avoid no-upstream push skip when base cannot be resolved
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex c8974ede6d refactor: dedupe git action new-branch flow
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marminge 0c637e3d5e Handle no-upstream branches by comparing commits against base
- Compute ahead count from base branch when upstream is missing
- Skip push/PR actions when no local commits are ahead
- Update server and UI tests for no-upstream push/PR behavior
2026-03-01 20:06:01 -08:00
Julius Marminge 0e2d50a620 Require ahead commits before offering Create PR on untracked branches
- Change quick action to `Push` (not `Push & create PR`) when branch has no upstream and is not ahead
- Keep `Create PR` menu item disabled until the branch has commits ahead
- Add/adjust logic tests for both no-ahead and ahead scenarios
2026-03-01 20:06:01 -08:00
Julius Marminge f3b3c54859 Add coverage for no-upstream default-branch quick actions
- test push-only quick action on default branch without upstream
- verify push and create PR stay disabled when branch is behind
2026-03-01 20:06:01 -08:00
Julius Marminge 02eca40c3b Enable push/PR actions for branches without upstream
- Treat no-upstream branches as publishable: enable Push/Create PR and update quick actions
- Route Create PR menu action through commit+push+PR flow when appropriate
- Simplify Git action dialog to commit-only and add "Commit on new branch" option
2026-03-01 20:06:01 -08:00
Julius Marminge c6ee3aee9f Add default-branch safeguard with auto feature branch fallback
- Prompt before commit/push actions on the default branch
- Allow one-click create+checkout of an auto-named feature branch and continue
- Add logic/tests for date-based unique auto feature branch naming
2026-03-01 20:06:01 -08:00
Julius Marminge 586e0ecea9 Document lint and typecheck completion requirements
- add a Task Completion Requirements section to AGENTS.md
- require `bun lint` and `bun typecheck` before marking tasks done
2026-03-01 19:57:50 -08:00
Julius Marminge dcd18413a2 Update contracts description to effect/Schema in AGENTS.md
- Clarify that `packages/contracts` uses effect/Schema schemas instead of Zod
2026-03-01 19:45:11 -08:00
Julius Marminge 73f296b4cf type 2026-03-01 18:49:12 -08:00
Julius Marminge 1419bf3989 fix? 2026-03-01 18:41:36 -08:00
Julius Marminge dca85c402c prep npm 2026-03-01 18:18:47 -08:00
Julius Marminge 56a3ad0f8b kewl 2026-03-01 18:18:47 -08:00
Julius Marminge 36f484c25a verbose in ci 2026-03-01 18:18:47 -08:00
Julius Marminge 03c6685097 kewl 2026-03-01 18:18:47 -08:00
Julius Marminge 23afddfbf9 Add tagged desktop release pipeline and unified artifact builder
- add GitHub Actions release workflow for v*.*.* tags with preflight checks
- build and publish macOS, Linux, and Windows desktop artifacts in one release
- replace DMG-only script with cross-platform `dist:desktop:artifact` flow
- document release, signing setup, and new desktop dist commands
2026-03-01 18:18:47 -08:00
Julius Marminge e3a2dfb9d0 Fix diff panel padding and top spacing for virtualized files
- Use horizontal and bottom padding on the diff render surface
- Add top margin to the first diff file for consistent spacing
2026-03-01 10:31:13 -08:00
Julius Marminge 3dd004c323 Keep diff panel header sticky while scrolling
- Make the diffs header stick to the top of the panel
- Add header background and bottom border for readability
2026-03-01 10:31:13 -08:00
Julius Marminge 1af43dbf90 Handle remote checkout conflicts without duplicate local branch
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
2026-02-28 21:56:22 -08:00
Julius Marminge 16fed12dcc Handle remote lookup failures in branch listing
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
2026-02-28 21:56:22 -08:00
Julius Marminge 29825f2f8a Filter detached HEAD pseudo-refs from branch listings
- ignore branch lines starting with `(` when parsing `git branch` output
- add integration test to verify detached HEAD does not appear as a branch
2026-02-28 21:56:22 -08:00
Julius Marminge efcee4b863 Handle branch checkout and dedupe for slash-named remotes
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
2026-02-28 21:56:22 -08:00
Julius Marminge 26edcab8b4 Reorder sidebar thread status badges and title layout
- Move PR status indicator into the main thread info row
- Keep thread status badge and title grouped for consistent alignment
2026-02-28 21:56:22 -08:00
Julius Marminge c626892adf Hide duplicate remote branches when local branch exists
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
2026-02-28 21:56:22 -08:00
Julius Marminge 3c66cdf2fe Support remote branch listing and tracking checkout flow
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
2026-02-28 21:56:22 -08:00
Julius Marminge db31c36213 Open diff files in editor from diff header clicks
- Add click handling on diff file headers (`data-title`) to open files via native `openInEditor`
- Resolve file paths against active thread/project cwd before launching editor
- Add header hover affordance and tighten diff panel spacing
2026-02-28 21:30:05 -08:00
Julius Marminge cafe3352f1 Remove redundant PR status title attribute
- Drop `title` from the PR status button in `Sidebar` to avoid duplicate tooltip text
2026-02-28 16:24:03 -08:00
Julius Marminge 7a39ce34fa Avoid popup-open false errors on mobile browsers
- Stop throwing when `window.open` returns `null` in `wsNativeApi`
- Keep opening external links in a new tab and rely on browser popup policy
2026-02-28 16:24:03 -08:00
Julius Marmingeandcodex 483702df77 Add clickable PR status tooltip in sidebar threads
- Show PR number/title in a tooltip on each thread PR icon
- Open PR links externally from the sidebar and show error toasts on failure
- Improve thread row keyboard handling after switching to a non-button render

Co-authored-by: codex <[email protected]>
2026-02-28 16:24:03 -08:00
Julius Marminge 206eb6a785 even better 2026-02-28 15:17:03 -08:00
Julius Marminge de9ec2bc73 kewl 2026-02-28 15:17:03 -08:00
Julius Marminge 1a66e517cd simp 2026-02-28 15:17:03 -08:00
Julius Marminge 33e6f35ce9 simp 2026-02-28 15:17:03 -08:00
Julius Marminge e8896fe02d Add copy button to chat markdown code blocks
- Wrap rendered markdown code blocks with a copy action button
- Show copy/check icons with transient "Copied" state and cleanup
- Style button to appear on hover/focus without shifting code layout
2026-02-28 15:17:03 -08:00
Julius Marminge e89b053269 Fix code highlight cache behavior for streaming markdown
- Reuse in-flight highlight requests and allow later non-streaming renders to cache results
- Stabilize code block highlight state updates to avoid stale or redundant rerenders
- Export and reuse `fnv1a32` from `diffRendering` for shared cache key hashing
2026-02-28 15:17:03 -08:00
Julius Marminge d052d481d8 Move diff theme overrides into DiffPanel unsafeCSS
- Inject diff palette overrides via `unsafeCSS` in `DiffPanel`
- Add `diff-panel-viewport` background and keep file container border/background styling in `index.css`
- Switch panel root from `bg-card` to `bg-background` for consistent surface tone
2026-02-28 15:17:03 -08:00
Julius Marminge fcbb494af7 Align diff panel surfaces with app theme colors
- add diff-specific wrapper classes in `DiffPanel` for targeted theming
- override diff renderer color variables to match card/background palette
- soften chat markdown Shiki code-block background for consistency
2026-02-28 15:17:03 -08:00
Julius Marminge 2980a853e5 Use shared Shiki highlighting for chat markdown code blocks
- Replace `rehype-highlight`/`highlight.js` with `@pierre/diffs` highlighter in `ChatMarkdown`
- Add LRU caching and in-flight dedupe for highlighted code, with streaming-aware behavior
- Extract shared diff theme resolution utility and add unit tests for new LRU cache
2026-02-28 15:17:03 -08:00
Theo Browne 56de1465fa feat: custom models (#121)
* custom models

* better fake version
2026-02-28 14:42:10 -08:00
Julius Marminge b500106fde Merge pull request #122 from pingdotgg/codething/10276f55 2026-02-28 11:33:43 -08:00
Julius Marminge 7f2a95fe14 Prefer open PR when resolving git status PR
- Update GitManager PR selection to return the latest open PR before merged ones
- Add regression test covering open-vs-merged ordering by updatedAt
2026-02-28 11:10:18 -08:00
Julius Marminge 4b3825e500 Merge remote-tracking branch 'origin/main' into codething/10276f55 2026-02-27 21:33:39 -08:00
Julius Marminge d48b42c017 fix type 2026-02-27 21:32:15 -08:00
Julius Marminge fb45896588 simplify layers 2026-02-27 21:30:46 -08:00
Julius Marminge b52518f85f Flatten attachment paths with message-prefixed filenames
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
2026-02-27 21:30:46 -08:00
Julius Marminge 3e99019af8 Serve attachments using URL-encoded relative paths
- Read attachment route paths without URI decoding before normalization
- Align test fixture paths with encoded thread/message/file names
2026-02-27 21:30:46 -08:00
Julius Marminge 7d4b02689e Overwrite attachment bytes for repeated message attachment index
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
2026-02-27 21:30:46 -08:00
Julius Marminge 9962f57ad0 Preserve empty attachment updates in projection pipeline
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
2026-02-27 21:30:46 -08:00
Julius Marminge 8b538e2802 dedupe 2026-02-27 21:30:46 -08:00
Julius Marminge a6c57e169a nit 2026-02-27 21:30:46 -08:00
Julius Marminge 6f92f0a668 kewl 2026-02-27 21:30:46 -08:00
Julius Marminge 35817601ff fixxx 2026-02-27 21:30:46 -08:00
Julius Marminge 2b154db938 Add gallery navigation to expanded chat image previews
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
2026-02-27 21:30:46 -08:00
Julius Marminge b9ff7aa5cd Make attachment writes transactional and decode attachment URLs
- Stage attachment file writes until projector transactions commit, then apply write/prune/delete side effects
- Remove orphaned attachment files on thread revert and delete thread attachment dirs on thread deletion
- Serve URL-encoded attachment paths in `wsServer` and stream file responses
- Add regression tests for rollback safety, revert/delete cleanup, and encoded attachment URLs
2026-02-27 21:30:46 -08:00
Julius Marminge b5188e8cea Harden attachment materialization and static file path handling
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
2026-02-27 21:30:46 -08:00
Julius Marminge 992db16586 Persist and serve projected message image attachments
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
2026-02-27 21:30:46 -08:00
Julius Marminge 2aad749e24 Reuse persisted cwd when recovering stale provider sessions
- Read and validate `cwd` from persisted runtime payload when restarting sessions
- Apply persisted `cwd` during stale-session recovery paths, including `sendTurn`
- Add tests to verify resumed sessions preserve the original working directory
2026-02-27 20:58:21 -08:00
Julius Marminge aa267ebb05 clamp 2026-02-27 19:27:05 -08:00
Cursor AgentandJulius Marminge 1a33f25970 web: keep active turn out of virtualization
Co-authored-by: Julius Marminge <[email protected]>
2026-02-27 19:27:05 -08:00
Julius Marmingeandcodex e8dfc42f44 Merge origin/main into codething/4efb5794
Co-authored-by: codex <[email protected]>
2026-02-27 18:21:47 -08:00
Julius Marminge 21c823ecdc Guard delayed terminal exit callback
- Skip `onSessionExited` if exit handling was reset before timeout runs
- Prevent stale async exit callbacks from firing in terminal drawer
2026-02-27 18:08:18 -08:00
Julius Marminge 80498f1709 Handle terminal exit writes and auto-close exited terminal view
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
2026-02-27 18:08:18 -08:00
Julius Marmingeandcodex 37e17e9207 Merge origin/main into codething/4efb5794
Co-authored-by: codex <[email protected]>
2026-02-19 16:12:13 -08:00
Julius Marmingeandcodex fe86836b43 Merge origin/main and resolve PR status/sidebar conflicts
Co-authored-by: codex <[email protected]>
2026-02-16 01:01:13 -08:00
Julius Marminge 973e62373e Unify git status PR info into a single pr field
- Replace `openPr`/`mergedPr` with `pr` in server and contracts
- Add PR `state` (`open`/`closed`/`merged`) to git status schema
- Resolve latest branch PR via `gh pr list --state all` sorted by `updatedAt`
2026-02-15 19:46:24 -08:00
Julius Marminge dcdb9ac923 Skip local-branch PR checks and dedupe sidebar git status
- server: only query open PRs when the current branch has an upstream; still fall back to merged PR lookup
- tests: cover status behavior for branches without upstream tracking
- web: fetch git status once per cwd, validate query data with schema parsing, and map merged PR badges by thread branch match
2026-02-15 14:28:03 -08:00
Julius Marminge 46347e2bd2 Show merged PR status when no open PR exists
- extend `GitStatusResult` with nullable `mergedPr` metadata
- in server git status, query merged PR only when no open PR is found
- in sidebar, display a `Merged` status pill for threads on branches with merged PRs
- update server/web/contracts tests for the new status shape
2026-02-15 14:04:48 -08:00
1209 changed files with 309031 additions and 29892 deletions

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
---
name: btca-cli
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
---
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
For example, assuming you have a resource named `codex`, you can ask questions like:
```bash
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
```
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
New resources can be created if the ones you need do not yet exist.
```bash
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
```
@@ -1,3 +0,0 @@
interface:
display_name: "BTCA CLI"
short_description: "Help with BTCA CLI setup and usage workflows"
+1
View File
@@ -0,0 +1 @@
plans/
+29
View File
@@ -0,0 +1,29 @@
{
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "24.13.1"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.10",
"installTools": false
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
"customizations": {
"vscode": {
"extensions": ["oxc.oxc-vscode"]
}
}
}
+143
View File
@@ -0,0 +1,143 @@
# Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ wsTransport (state machine) │
│ Typed push decode at boundary │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ServerPushBus (ordered pushes) │
│ ServerReadiness (startup gate) │
│ OrchestrationEngine │
│ ProviderService │
│ CheckpointReactor │
│ RuntimeReceiptBus │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Components
- **Browser app**: The React app renders session state, owns the client-side WebSocket transport, and treats typed push events as the boundary between server runtime details and UI state.
- **Server**: `apps/server` is the main coordinator. It serves the web app, accepts WebSocket requests, waits for startup readiness before welcoming clients, and sends all outbound pushes through a single ordered push path.
- **Provider runtime**: `codex app-server` does the actual provider/session work. The server talks to it over JSON-RPC on stdio and translates those runtime events into the app's orchestration model.
- **Background workers**: Long-running async flows such as runtime ingestion, command reaction, and checkpoint processing run as queue-backed workers. This keeps work ordered, reduces timing races, and gives tests a deterministic way to wait for the system to go idle.
- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state.
## Event Lifecycle
### Startup and client connect
```mermaid
sequenceDiagram
participant Browser
participant Transport as WsTransport
participant Server as wsServer
participant Layers as serverLayers
participant Ready as ServerReadiness
participant Push as ServerPushBus
Browser->>Transport: Load app and open WebSocket
Transport->>Server: Connect
Server->>Layers: Start runtime services
Server->>Ready: Wait for startup barriers
Ready-->>Server: Ready
Server->>Push: Publish server.welcome
Push-->>Transport: Ordered welcome push
Transport-->>Browser: Hydrate initial state
```
1. The browser boots [`WsTransport`][1] and registers typed listeners in [`wsNativeApi`][2].
2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7].
3. [`ServerReadiness`][4] waits until the key startup barriers are complete.
4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5].
5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] uses it to seed local client state.
### User turn flow
```mermaid
sequenceDiagram
participant Browser
participant Transport as WsTransport
participant Server as wsServer
participant Provider as ProviderService
participant Codex as codex app-server
participant Ingest as ProviderRuntimeIngestion
participant Engine as OrchestrationEngine
participant Push as ServerPushBus
Browser->>Transport: Send user action
Transport->>Server: Typed WebSocket request
Server->>Provider: Route request
Provider->>Codex: JSON-RPC over stdio
Codex-->>Ingest: Provider runtime events
Ingest->>Engine: Normalize into orchestration events
Engine-->>Server: Domain events
Server->>Push: Publish orchestration.domainEvent
Push-->>Browser: Typed push
```
1. A user action in the browser becomes a typed request through [`WsTransport`][1] and the browser API layer in [`nativeApi`][12].
2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] and routes it to the right service.
3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio.
4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events.
5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events.
6. [`wsServer`][3] pushes those updates to the browser through [`ServerPushBus`][5] on channels defined in [`orchestration.ts`][11].
### Async completion flow
```mermaid
sequenceDiagram
participant Server as wsServer
participant Worker as Queue-backed workers
participant Cmd as ProviderCommandReactor
participant Checkpoint as CheckpointReactor
participant Receipt as RuntimeReceiptBus
participant Push as ServerPushBus
participant Browser
Server->>Worker: Enqueue follow-up work
Worker->>Cmd: Process provider commands
Worker->>Checkpoint: Process checkpoint tasks
Checkpoint->>Receipt: Publish completion receipt
Cmd-->>Server: Produce orchestration changes
Checkpoint-->>Server: Produce orchestration changes
Server->>Push: Publish resulting state updates
Push-->>Browser: User-visible push
```
1. Some work continues after the initial request returns, especially in [`ProviderRuntimeIngestion`][9], [`ProviderCommandReactor`][13], and [`CheckpointReactor`][14].
2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic.
3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence.
4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers.
5. Any user-visible state changes produced by that async work still go back through [`wsServer`][3] and [`ServerPushBus`][5].
[1]: ../apps/web/src/wsTransport.ts
[2]: ../apps/web/src/wsNativeApi.ts
[3]: ../apps/server/src/wsServer.ts
[4]: ../apps/server/src/wsServer/readiness.ts
[5]: ../apps/server/src/wsServer/pushBus.ts
[6]: ../packages/contracts/src/ws.ts
[7]: ../apps/server/src/serverLayers.ts
[8]: ../apps/server/src/provider/Layers/ProviderService.ts
[9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[11]: ../packages/contracts/src/orchestration.ts
[12]: ../apps/web/src/nativeApi.ts
[13]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[14]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[15]: ../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
[16]: ../packages/shared/src/DrainableWorker.ts
+6
View File
@@ -0,0 +1,6 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+5
View File
@@ -0,0 +1,5 @@
# Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
+180
View File
@@ -0,0 +1,180 @@
# Encyclopedia
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
## Concepts
### Project and workspace
#### Project
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13].
Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6].
#### Quiesced
"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6].
### Provider runtime
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16].
#### Provider
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18].
#### Interaction mode
The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18].
#### Assistant delivery mode
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
- If you see `completed`, think "result applied".
- If you see `receipt`, think "async milestone signal".
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
## Related Docs
- [architecture.md][24]
- [provider-architecture.md][16]
- [runtime-modes.md][18]
- [workspace-layout.md][2]
[1]: ../packages/contracts/src/orchestration.ts
[2]: ./workspace-layout.md
[3]: ../apps/server/src/git/Layers/GitCore.ts
[4]: ../apps/server/src/orchestration/projector.ts
[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[8]: ../apps/server/src/orchestration/decider.ts
[9]: ../apps/server/src/orchestration/commandInvariants.ts
[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
[14]: ../apps/server/src/provider/Layers/ProviderService.ts
[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts
[16]: ./provider-architecture.md
[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts
[18]: ./runtime-modes.md
[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts
[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
[22]: ../apps/server/src/checkpointing/Utils.ts
[23]: ../apps/server/src/checkpointing/Diffs.ts
[24]: ./architecture.md
+30
View File
@@ -0,0 +1,30 @@
# Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: typed envelopes with `channel`, `sequence` (monotonic per connection), and channel-specific `data`
Push channels: `server.welcome`, `server.configUpdated`, `terminal.event`, `orchestration.domainEvent`. Payloads are schema-validated at the transport boundary (`wsTransport.ts`). Decode failures produce structured `WsDecodeDiagnostic` with `code`, `reason`, and path info.
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## Client transport
`wsTransport.ts` manages connection state: `connecting` → `open` → `reconnecting` → `closed` → `disposed`. Outbound requests are queued while disconnected and flushed on reconnect. Inbound pushes are decoded and validated at the boundary, then cached per channel. Subscribers can opt into `replayLatest` to receive the last push on subscribe.
## Server-side orchestration layers
Provider runtime events flow through queue-based workers:
1. **ProviderRuntimeIngestion** — consumes provider runtime streams, emits orchestration commands
2. **ProviderCommandReactor** — reacts to orchestration intent events, dispatches provider calls
3. **CheckpointReactor** — captures git checkpoints on turn start/complete, publishes runtime receipts
All three use `DrainableWorker` internally and expose `drain()` for deterministic test synchronization.
+22
View File
@@ -0,0 +1,22 @@
# Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
+382
View File
@@ -0,0 +1,382 @@
# 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.
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
### 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.
### AdvertisedEndpoint
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
`AdvertisedEndpoint` is deliberately narrower than the full access model:
- it describes a concrete HTTP and WebSocket base URL pair
- it can mark the endpoint as default, available, or unavailable
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
When no user default is saved, endpoint selection should prefer:
1. endpoints compatible with the hosted HTTPS app
2. explicitly default endpoints
3. non-loopback endpoints
4. loopback endpoints only for same-machine clients
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
### Endpoint providers
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
The provider boundary is intentionally outside the core environment model:
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
- providers discover or synthesize endpoints
- providers return normalized `AdvertisedEndpoint` records
- the UI and pairing logic select from those records without knowing provider-specific commands
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
Example:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
Important constraints:
- the hosted app does not proxy HTTP or WebSocket traffic
- the backend must still be reachable directly from the browser
- HTTPS pages can only connect to HTTPS/WSS backends
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
- the token belongs in the URL hash so it is not sent to the hosted app origin
### 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
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
### 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
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
### 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.
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
## 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.
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
Failure handling should be explicit:
- SSH authentication failure should surface before any environment is saved
- remote launch failure should include remote logs or the launcher command output when available
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
### 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.
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
## 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.
+6
View File
@@ -0,0 +1,6 @@
# Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
+42
View File
@@ -0,0 +1,42 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --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.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
## Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
+7
View File
@@ -0,0 +1,7 @@
# Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `/packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`, `@t3tools/shared/DrainableWorker`) — no barrel index.
+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.
+35
View File
@@ -0,0 +1,35 @@
# Trust list for this repository.
#
# External contributors listed here are treated as trusted by the vouch
# workflow. Collaborators with write access are automatically trusted and
# do not need to be duplicated in this file.
#
# Syntax:
# github:username
# -github:username reason for denouncement
#
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+33
View File
@@ -0,0 +1,33 @@
<!--
⚠️ READ BEFORE OPENING ⚠️
We are not actively accepting contributions right now.
You can still open a PR, but please do so knowing there is a high chance
we may close it without merging it, or never review it.
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
- New features will most likely just annoy us.
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
-->
## What Changed
<!-- Describe the change clearly and keep scope tight. -->
## Why
<!-- Explain the problem being solved and why this approach is the right one. -->
## UI Changes
<!-- If this PR changes UI, include clear before/after screenshots.
If the change involves motion or interaction, include a short video.
Delete this section if not applicable. -->
## Checklist
- [ ] This PR is small and focused
- [ ] I explained what changed and why
- [ ] I included before/after screenshots for any UI changes
- [ ] I included a video for animation/interaction changes
+51 -7
View File
@@ -8,11 +8,12 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-8vcpu-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
@@ -34,9 +35,20 @@ jobs:
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
@@ -46,10 +58,42 @@ jobs:
- name: Test
run: bun run test
- name: Install browser test runtime
run: |
cd apps/web
bunx playwright install --with-deps chromium
- name: Browser test
run: bun run --cwd apps/web test:browser
- name: Build desktop pipeline
run: bun run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+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,
});
}
}
+295
View File
@@ -0,0 +1,295 @@
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:
# This pull_request_target job may fetch untrusted PR commits only as passive
# git data. Do not add dependency installs, build/test scripts, or cache
# actions here; use pull_request plus workflow_run for that pattern instead.
- 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})`,
);
+199
View File
@@ -0,0 +1,199 @@
name: PR Vouch
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
issue_comment:
types: [created]
push:
branches:
- main
paths:
- .github/VOUCHED.td
- .github/workflows/pr-vouch.yml
permissions:
contents: read
issues: write
pull-requests: write
jobs:
collect-targets:
name: Collect PR targets
runs-on: ubuntu-24.04
outputs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
with:
script: |
if (context.eventName === "pull_request_target") {
const pr = context.payload.pull_request;
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
return;
}
if (context.eventName === "issue_comment") {
const issue = context.payload.issue;
const body = context.payload.comment?.body ?? "";
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
core.setOutput("targets", "[]");
return;
}
core.setOutput(
"targets",
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
);
return;
}
const pulls = await github.paginate(github.rest.pulls.list, {
owner: context.repo.owner,
repo: context.repo.repo,
state: "open",
per_page: 100,
});
const targets = pulls.map((pull) => ({
number: pull.number,
user: pull.user.login,
}));
core.setOutput("targets", JSON.stringify(targets));
label:
name: Label PR ${{ matrix.target.number }}
needs: collect-targets
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
runs-on: ubuntu-24.04
concurrency:
group: pr-vouch-${{ matrix.target.number }}
cancel-in-progress: true
strategy:
fail-fast: false
matrix:
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
steps:
- id: vouch
name: Check PR author trust
uses: mitchellh/vouch/action/check-user@v1
with:
user: ${{ matrix.target.user }}
allow-fail: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
with:
script: |
const issueNumber = Number(process.env.PR_NUMBER);
const status = process.env.VOUCH_STATUS;
const managedLabels = [
{
name: "vouch:trusted",
color: "1f883d",
description: "PR author is trusted by repo permissions or the VOUCHED list.",
},
{
name: "vouch:unvouched",
color: "fbca04",
description: "PR author is not yet trusted in the VOUCHED list.",
},
{
name: "vouch:denounced",
color: "d1242f",
description: "PR author is explicitly blocked by the VOUCHED list.",
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
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;
}
}
}
}
const nextLabelName =
status === "denounced"
? "vouch:denounced"
: ["bot", "collaborator", "vouched"].includes(status)
? "vouch:trusted"
: "vouch:unvouched";
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],
});
}
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+805
View File
@@ -0,0 +1,805 @@
name: Release
on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: false
type: string
permissions:
contents: read
id-token: none
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: blacksmith-8vcpu-ubuntu-2404
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
fi
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- label: macOS arm64
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
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: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$installPath = & $vswhere -products * -latest -property installationPath
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
$proc = Start-Process -FilePath $setupExe `
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
-Wait -PassThru -NoNewWindow
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
Write-Error "Visual Studio Installer failed with exit code $code"
exit $code
}
- name: Prepare Azure Trusted Signing
if: matrix.platform == 'win'
shell: pwsh
env:
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
$ErrorActionPreference = "Stop"
$requiredSecrets = @(
$env:AZURE_TENANT_ID,
$env:AZURE_CLIENT_ID,
$env:AZURE_CLIENT_SECRET,
$env:AZURE_TRUSTED_SIGNING_ENDPOINT,
$env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME,
$env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME,
$env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME
)
if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation."
exit 0
}
try {
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser `
-ErrorAction Stop
} catch {
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
}
Install-Module `
-Name TrustedSigning `
-MinimumVersion 0.5.0 `
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
$moduleRoots = @(
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"),
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules")
)
$modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) |
Where-Object { $_ -and (Test-Path $_) } |
Select-Object -Unique
"PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV
- name: Build desktop artifact
shell: bash
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
args=(
--platform "${{ matrix.platform }}"
--target "${{ matrix.target }}"
--arch "${{ matrix.arch }}"
--build-version "${{ needs.preflight.outputs.version }}"
--verbose
)
has_all() {
for value in "$@"; do
if [[ -z "$value" ]]; then
return 1
fi
done
return 0
}
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
echo "macOS signing enabled."
args+=(--signed)
else
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
"$AZURE_CLIENT_SECRET" \
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
echo "Windows signing enabled (Azure Trusted Signing)."
args+=(--signed)
else
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
fi
else
echo "Signing disabled for ${{ matrix.platform }}."
fi
bun run dist:desktop:artifact -- "${args[@]}"
- name: Collect release assets
shell: bash
run: |
set -euo pipefail
mkdir -p release-publish
shopt -s nullglob
for pattern in \
"release/*.dmg" \
"release/*.zip" \
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
if-no-files-found: error
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: bun --filter=@t3tools/web run build
- name: Build CLI package
run: bun --filter=t3 run build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
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@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
with:
pattern: desktop-*
merge-multiple: true
path: release-assets
- name: Merge macOS updater manifests
run: |
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }}
T3CODE_WEB_LATEST_DOMAIN: ${{ vars.T3CODE_WEB_LATEST_DOMAIN }}
T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install release tooling dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts --filter=@t3tools/web
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: bun install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
router_domain="${router_url#http://}"
router_domain="${router_domain#https://}"
router_domain="${router_domain%%/*}"
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
channel_domain="$latest_domain"
channel_name="latest"
else
channel_domain="$nightly_domain"
channel_name="nightly"
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
vercel_scope_args=(--scope "$vercel_scope")
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
bunx [email protected] deploy \
--prod \
--skip-domain \
--yes \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
echo "Aliasing $deployment_url to $channel_domain."
bunx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
bunx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
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@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
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- id: update_versions
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx [email protected] apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
shell: bash
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
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"
git push origin HEAD:main
announce_discord:
name: Announce release on Discord
if: |
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
needs.deploy_web.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, deploy_web, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts prerelease \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
- name: Announce latest release on Discord
if: needs.preflight.outputs.make_latest == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts latest \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
+15 -1
View File
@@ -5,10 +5,24 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
.astro
packages/*/dist
.env
.env.local
build/
.logs/
release/
.t3
release-mock/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+3
View File
@@ -0,0 +1,3 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
+14 -2
View File
@@ -1,13 +1,25 @@
{
"$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",
"*.icon/**"
],
"experimentalSortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+4 -1
View File
@@ -9,6 +9,7 @@
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
@@ -17,6 +18,8 @@
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"eslint/no-await-in-loop": "off",
"eslint/no-underscore-dangle": "off",
"t3code/no-inline-schema-compile": "warn"
}
}
+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`.
-546
View File
@@ -1,546 +0,0 @@
# 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
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. `ProviderService.startSession` currently defaults to `provider: "codex"` unless explicitly provided.
3. `thread.turn.start` has no provider field today, so first-turn provider selection cannot be explicitly requested.
4. `ProviderService` 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
Update `packages/contracts/src/provider.ts`:
1. Extend `ProviderSessionStartInput` with optional Claude-specific fields (for example `claudeBinaryPath`, `permissionMode`, `maxThinkingTokens`).
2. Keep fields optional so current call sites remain valid.
3. Continue using generic `resumeThreadId` + `resumeCursor` as the cross-provider recovery mechanism.
### 1.4 Contract tests
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Backward compatibility of existing command/schema decoding.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.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 `claudeBinaryPath`)
4. `permissionMode`
5. `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 `resumeThreadId` / `resumeCursor`.
#### 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`.
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 abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(input.sessionId),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: input.permissionMode,
maxThinkingTokens: input.maxThinkingTokens,
pathToClaudeCodeExecutable: input.claudeBinaryPath,
resume: input.resumeThreadId,
resumeSessionAt: readResumeCursor(input.resumeCursor),
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(input.sessionId),
hooks: makeClaudeHooks(input.sessionId),
},
});
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 queue = yield* Queue.unbounded<ClaudeSdkMessage>();
yield* Effect.forkScoped(
Effect.tryPromise({
try: async () => {
for await (const message of session.result) {
Queue.offerAllUnsafe(queue, [message]);
}
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream pump failed.",
cause,
}),
}),
);
const sdkMessageStream = Stream.fromQueue(queue);
```
#### 2.2.d Multi-turn prompt queue pattern (Effect)
Use an Effect queue as the single input boundary:
```ts
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
[Symbol.asyncIterator]() {
return {
next: async () => {
const item = await Effect.runPromise(Queue.take(promptQueue));
if (item.type === "terminate") {
return { done: true, value: undefined };
}
return { done: false, value: item };
},
};
},
};
```
`sendTurn()` enqueues a user envelope, while `stopSession()` enqueues terminate and aborts.
#### 2.2.e Approval bridge with `canUseTool`
Map SDK approval checks to existing orchestration approval flows:
```ts
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
if (approvalModeIsFullAccess(sessionId)) {
return { behavior: "allow", updatedInput: toolInput };
}
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
emitRuntimeEvent({
type: "approval.requested",
provider: "claudeCode",
sessionId,
requestId,
requestKind: classifyTool(toolName),
detail: summarizeToolRequest(toolName, toolInput),
// ... eventId/createdAt
});
const decision = await waitForApprovalDecision(requestId);
emitRuntimeEvent({
type: "approval.resolved",
provider: "claudeCode",
sessionId,
requestId,
decision,
// ... eventId/createdAt
});
return decision === "accept" || decision === "acceptForSession"
? { behavior: "allow", updatedInput: toolInput }
: { behavior: "deny", message: "User declined tool execution." };
};
```
#### 2.2.f Hooks and checkpoint signals
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (`turn.completed` and optionally `checkpoint.captured`) so `CheckpointReactor` remains unchanged:
```ts
hooks: {
Stop: [
{
matcher: {},
hooks: [
async () => {
emitRuntimeEvent({
type: "checkpoint.captured",
provider: "claudeCode",
sessionId,
threadId,
turnId: activeTurnId,
turnCount: nextTurnCount(),
// ... eventId/createdAt
});
},
],
},
],
}
```
#### 2.2.g Runtime control method wiring
Adapter should expose SDK controls through existing service methods and runtime payload updates:
1. `interruptTurn()` -> `result.interrupt()`
2. Model override on send turn -> `result.setModel(model)` before enqueuing prompt
3. Runtime mode changes -> `result.setPermissionMode(mode)` if we support live mode switching
4. Thinking budget updates -> `result.setMaxThinkingTokens(tokens)` when configured
### 2.3 Canonical event mapping
Map Claude SDK events to `ProviderRuntimeEvent`:
1. `session.started` / `session.exited`
2. `turn.started` / `turn.completed`
3. `message.delta` / `message.completed`
4. `tool.started` / `tool.completed`
5. `approval.requested` / `approval.resolved`
6. `runtime.error`
No provider-native event methods should leak beyond the adapter boundary.
Reference mapping table:
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|---|---|---|
| assistant partial text | `message.delta` | Emit deltas only (do not resend full content each chunk). |
| assistant final message | `message.completed` | Must include stable `itemId` for dedupe/finalize behavior. |
| result (success) | `turn.completed` (`status: "completed"`) | This is the main turn boundary for checkpointing. |
| result (interrupted/cancelled) | `turn.completed` (`status: "interrupted"`/`"cancelled"`) | Preserve state semantics used by ingestion + UI. |
| result (error) | `runtime.error` and `turn.completed` (`status: "failed"`) | Include concise error message. |
| tool start | `tool.started` | Set `toolKind` using shared classifier (`command`, `file-change`, `other`). |
| tool result | `tool.completed` | Include detail summary used by activity feed. |
| canUseTool prompt | `approval.requested` | Source of request id shown in UI. |
| approval decision returned | `approval.resolved` | Must correlate using same request id. |
| session initialization | `session.started`, optional `thread.started` | Ensure `threadId` is emitted early and consistently. |
| process exit/close | `session.exited` | Required for session status projection cleanup. |
### 2.4 Session/thread/resume identifiers
Define explicit adapter semantics:
1. `sessionId`: adapter-owned stable session id.
2. `threadId`: Claude conversation/session identifier returned as `ProviderThreadId`.
3. `resumeCursor`: provider-specific cursor (for example message id) needed for precise recovery/rollback.
### 2.5 Rollback/read strategy
Implement `readThread()` and `rollbackThread()` in a way compatible with `CheckpointReactor`.
Preferred:
1. Track per-turn resume cursors and reconstruct session state on rollback.
2. Keep adapter `sessionId` stable across internal rehydration/restart.
Fallback (explicitly documented if chosen):
1. Filesystem revert succeeds even when conversation rewind is partial.
2. Reactor behavior is updated to surface a clear warning activity instead of silent drift.
### 2.6 Adapter unit tests
Add tests mirroring Codex adapter coverage:
1. Provider validation (`provider === "claudeCode"`).
2. Event mapping to canonical runtime events.
3. Approval request lifecycle.
4. Resume/recovery behavior.
5. Rollback behavior.
---
## Phase 3: Register adapter in runtime composition
### 3.1 Adapter registry wiring
Update:
1. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
Register both Codex and Claude adapters.
### 3.2 Server layer composition
Update:
1. `apps/server/src/serverLayers.ts`
Provide `ClaudeCodeAdapterLive` alongside Codex in `makeServerProviderLayer()`.
### 3.3 Composition tests
Update integration tests to ensure:
1. Registry exposes Claude provider.
2. Provider service can route Claude sessions.
---
## Phase 4: Orchestration command/reactor updates
### 4.1 Decider propagation
Update `apps/server/src/orchestration/decider.ts`:
1. Carry optional `provider` from `thread.turn.start` command into `thread.turn-start-requested` event payload.
### 4.2 ProviderCommandReactor provider selection
Update `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`:
1. Prefer provider from turn-start event payload when starting a new session.
2. Fallback to existing thread session provider when payload omitted.
3. Fallback to default provider only when neither is present.
Switch behavior policy (explicit in implementation):
1. If active session provider differs from requested provider, stop and recreate session before sending turn.
2. Keep current provider when request omits provider.
### 4.3 Reactor/invariant tests
Update/add tests in:
1. `apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts`
2. `apps/server/src/orchestration/*.test.ts` as needed
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
---
## Phase 5: Web provider UX enablement
### 5.1 Enable Claude option
Update `apps/web/src/session-logic.ts`:
1. Mark Claude provider option as available.
### 5.2 Provider selection in composer
Update `apps/web/src/components/ChatView.tsx`:
1. Add provider picker near model/runtime controls.
2. Include selected provider in `thread.turn.start` command payload.
3. Keep selected provider sticky per thread in client state (or derive from active session provider when present).
### 5.3 Provider-aware model picker
Update model picker usage so model options reflect selected provider.
### 5.4 Web tests
Update/add tests for:
1. Provider picker interactions.
2. Turn-start command includes provider.
3. Model list switches by provider.
---
## Phase 6: Checkpoint and revert compatibility
### 6.1 Validate checkpoint reactor expectations
Exercise `apps/server/src/orchestration/Layers/CheckpointReactor.ts` flows with Claude:
1. Turn baseline capture.
2. Turn completion checkpoint capture.
3. Revert + provider rollback coordination.
### 6.2 Policy for partial rollback support
If Claude cannot support full conversation rewind at parity with Codex:
1. Document behavior clearly.
2. Emit explicit thread activity for degraded rollback behavior.
3. Ensure filesystem state remains correct and predictable.
### 6.3 Checkpoint tests
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
---
## Phase 7: End-to-end hardening and observability
### 7.1 Integration tests
Add integration coverage for:
1. `thread.turn.start` with `provider: "claudeCode"` from fresh thread.
2. Session recovery after restart (provider session alias/recovery path).
3. Approval request/respond flow.
4. Interrupt behavior.
5. Revert flow with rollback.
### 7.2 WS behavior regression check
Ensure no contract regressions:
1. Client still consumes only `orchestration.domainEvent`.
2. No new provider-specific WS channels introduced.
### 7.3 Logging
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
1. `provider-native.ndjson`
2. `provider-canonical.ndjson`
---
## File checklist
Likely files to touch:
1. `packages/contracts/src/model.ts`
2. `packages/contracts/src/orchestration.ts`
3. `packages/contracts/src/provider.ts`
4. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts` (new)
5. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts` (new)
6. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
7. `apps/server/src/serverLayers.ts`
8. `apps/server/src/orchestration/decider.ts`
9. `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
10. `apps/web/src/session-logic.ts`
11. `apps/web/src/components/ChatView.tsx`
12. Related tests under `packages/contracts/src`, `apps/server/src/provider/Layers`, `apps/server/src/orchestration/Layers`, `apps/server/integration`, and `apps/web/src`.
---
## Delivery order
1. Contracts for provider selection + models.
2. Claude adapter + unit tests.
3. Registry/layer wiring.
4. Reactor updates for provider-aware session start.
5. Web provider picker + provider-aware models.
6. Checkpoint/revert compatibility.
7. End-to-end integration tests and stabilization.
This order keeps risk isolated and maintains a working orchestrated path at each stage.
@@ -0,0 +1,109 @@
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
## 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 — 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 — 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 — 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 — 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 — 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 — 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 — 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 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.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
- ordering tests for `sequence`
- Server:
- readiness tests proving `server.welcome` cannot precede runtime readiness
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
- keybindings runtime tests with fake watch source plus one real watcher integration test
- Orchestration:
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
- replacement of polling-based checkpoint/integration waits with receipt-based waits
- Web:
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
- Validation gate:
- `bun run lint`
- `bun run typecheck`
- `mise exec -- bun run test`
- repeated full-suite run after cutover to confirm flake removal
## Assumptions and Defaults
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
- No backward-compatibility layer is required for old websocket push envelopes.
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
+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.
+349
View File
@@ -0,0 +1,349 @@
# Remote Endpoints and Hosted Static App Plan
## Purpose
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
```ts
type AdvertisedEndpointProvider =
| "loopback"
| "lan"
| "tailscale-ip"
| "tailscale-magicdns"
| "manual"
| "t3-tunnel";
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
type AdvertisedEndpointCompatibility = {
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
desktopApp: "compatible" | "unknown";
};
type AdvertisedEndpoint = {
id: string;
provider: AdvertisedEndpointProvider;
label: string;
httpBaseUrl: string;
wsBaseUrl: string;
visibility: AdvertisedEndpointVisibility;
compatibility: AdvertisedEndpointCompatibility;
source: "server" | "desktop" | "user";
status: "available" | "unavailable" | "unknown";
isDefault?: boolean;
};
```
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
## HTTP/WS and HTTPS/WSS Readiness
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
What is ready:
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
- Saved environments store both HTTP and WebSocket base URLs.
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
- WebSocket connections can use a dynamically issued `wsToken`.
- Server CORS support exists for browser remote auth endpoints.
What is not solved by code alone:
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
Policy:
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
- Mark endpoint compatibility at the product layer.
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
## Architecture
### Endpoint Sources
Endpoint records can come from several providers:
1. **Server runtime**
- headless bind host and port
- server-known explicit advertised host config
2. **Desktop shell**
- loopback backend URL
- LAN exposure state
- network interface discovery
- Tailscale CLI/status discovery
3. **User configuration**
- manually added hostnames
- preferred endpoint labels
- hidden/disabled endpoints
4. **Future cloud provider**
- T3 Tunnel endpoint
- billing/account status
- tunnel lifecycle state
### Endpoint Registry
Create a central runtime registry:
- `packages/contracts/src/remoteAccess.ts`
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
- `apps/server/src/remoteAccess/*` for server/headless endpoints
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
### Pairing Link Generation
Move hosted pairing link generation to endpoint-driven input:
```ts
buildHostedPairingUrl({
endpoint: AdvertisedEndpoint,
token,
});
```
Generated URL:
```text
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
```
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
## Phase 1: Endpoint Abstraction
### Goals
- Centralize URL normalization, protocol derivation, and compatibility checks.
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
- Preserve all current remote behavior.
### Tasks
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
2. Add shared helpers:
- normalize HTTP base URL
- derive WebSocket base URL
- classify loopback/private/LAN/Tailscale/public host
- classify hosted HTTPS compatibility
3. Add server endpoint discovery:
- loopback endpoint
- configured non-loopback endpoint
- explicit advertised host override
4. Add desktop endpoint discovery:
- local loopback
- LAN exposure endpoint
- endpoint status labels
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
- `app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
@@ -0,0 +1,216 @@
# Version Control Phase 1: VCS Driver Foundation
## Goal
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
- `Services/VcsDriver.ts`
- `Services/VcsRepositoryResolver.ts`
- `Services/VcsProcess.ts`
- `Layers/GitVcsDriver.ts`
- `errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
- `VcsDriver`: local repository mechanics.
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
- `RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
export interface VcsDriverCapabilities {
readonly kind: "git" | "jj" | "sapling" | "unknown";
readonly supportsWorktrees: boolean;
readonly supportsBookmarks: boolean;
readonly supportsAtomicSnapshot: boolean;
readonly supportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
- `detectRepository(cwd)`
- `status(cwd, options)`
- `listRefs(cwd, query/pagination)`
- `checkoutRef(cwd, ref)`
- `createRef(cwd, ref, from?)`
- `createWorkspace(cwd, ref, path?)`
- `removeWorkspace(path)`
- `prepareChangeContext(cwd, filePaths?)`
- `createChange(cwd, message, options)`
- `push(cwd, target?)`
- `rangeContext(cwd, base, head)`
- `listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
- `VcsProcessSpawnError`
- `VcsProcessExitError`
- `VcsProcessTimeoutError`
- `VcsOutputDecodeError`
- `VcsRepositoryDetectionError`
- `VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
```ts
export interface VcsFreshness {
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
readonly observedAt: string;
readonly expiresAt?: string;
}
```
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
@@ -0,0 +1,268 @@
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
- `Services/SourceControlProvider.ts`
- `Services/SourceControlProviderRegistry.ts`
- `Services/SourceControlProcess.ts`
- `Layers/GitHubSourceControlProvider.ts`
- `errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
- `SourceControlProvider`: hosted repository and change-request mechanics.
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
- `ChangeRequestThread`: review or discussion thread.
- `ChangeRequestComment`: top-level or inline comment.
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
Core provider operations:
- `detectRemote(remoteUrl)`
- `checkAuth(cwd)`
- `getRepository(cwd | remoteUrl)`
- `getDefaultTargetRef(repository)`
- `listChangeRequests(repository, filters)`
- `getChangeRequest(repository, reference)`
- `createChangeRequest(repository, input)`
- `checkoutChangeRequest(cwd, changeRequest, options)`
- `getCloneUrls(repository)`
Review-facing operations should be designed now, even if unimplemented:
- `listReviewThreads(changeRequest)`
- `createReviewComment(changeRequest, input)`
- `replyToReviewThread(thread, input)`
- `resolveReviewThread(thread)`
- `submitReview(changeRequest, input)`
Each operation should be guarded by capabilities:
```ts
export interface SourceControlProviderCapabilities {
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
readonly supportsCreateChangeRequest: boolean;
readonly supportsCheckoutChangeRequest: boolean;
readonly supportsReviewThreads: boolean;
readonly supportsInlineComments: boolean;
readonly supportsDraftChangeRequests: boolean;
}
```
## Provider Registry
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
The provider API should make freshness explicit:
```ts
export interface SourceControlFreshness {
readonly source: "live-local" | "cached-provider" | "live-provider";
readonly observedAt: string;
readonly expiresAt?: string;
readonly stale?: boolean;
}
export type ProviderRefreshPolicy =
| "cache-first"
| "stale-while-revalidate"
| "force-refresh"
| "local-only";
```
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
- `apps/server/src/git/Layers/GitHubCli.ts`
- `apps/server/src/git/Layers/GitHubCli.test.ts`
- `apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
- `VcsDriver` for local repository mechanics.
- `SourceControlProviderRegistry` for hosted provider selection.
- `TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
- `GitLabSourceControlProvider` using `glab`.
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- GitLab MR URL/reference parsing.
- Azure DevOps PR URL parsing for same-repo URLs.
- unknown provider returns unsupported-operation errors.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
- `GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
+2
View File
@@ -10,3 +10,5 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
+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`.
-64
View File
@@ -1,64 +0,0 @@
import path from "path";
import fs from "fs";
const FAVICON_CANDIDATES = [
"favicon.svg", "favicon.ico", "favicon.png",
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
];
const ICON_SOURCE_FILES = [
"index.html", "public/index.html",
"app/routes/__root.tsx", "src/routes/__root.tsx",
"app/root.tsx", "src/root.tsx", "src/index.html",
];
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
function test(projectCwd) {
console.log("--- Testing:", projectCwd, "---");
for (const c of FAVICON_CANDIDATES) {
const full = path.join(projectCwd, c);
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
console.log(" Phase 1 FOUND:", c);
return;
}
}
console.log(" Phase 1: no match");
for (const sf of ICON_SOURCE_FILES) {
const full = path.join(projectCwd, sf);
if (!fs.existsSync(full)) continue;
const content = fs.readFileSync(full, "utf8");
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
if (href) {
const clean = href.replace(/^\//, "");
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
for (const p of tryPaths) {
if (fs.existsSync(p)) {
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
return;
}
}
console.log(" Phase 2 href found but file missing:", href);
}
}
console.log(" Phase 2: no match");
}
function getTestPaths() {
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
if (cliPaths.length > 0) return cliPaths;
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
if (envPaths?.length) return envPaths;
return [process.cwd()];
}
for (const p of getTestPaths()) {
test(path.resolve(p));
}
+1 -1
View File
@@ -5,5 +5,5 @@
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"js/ts.tsdk.path": "node_modules/typescript/lib"
}
+13 -3
View File
@@ -1,8 +1,13 @@
# CLAUDE.md
# AGENTS.md
## Task Completion Requirements
- 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.
@@ -14,11 +19,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
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
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
## Codex App Server (Important)
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+65
View File
@@ -0,0 +1,65 @@
# Contributing
## Read This First
We are not actively accepting contributions right now.
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
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 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).
## What We Are Most Likely To Accept
Small, focused bug fixes.
Small reliability fixes.
Small performance improvements.
Tightly scoped maintenance work that clearly improves the project without changing its direction.
## What We Are Least Likely To Accept
Large PRs.
Drive-by feature work.
Opinionated rewrites.
Anything that expands product scope without us asking for it first.
If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions.
## If You Still Want To Open A PR
Keep it small.
Explain exactly what changed.
Explain exactly why the change should exist.
Do not mix unrelated fixes together.
If the PR makes anything resembling a UI change, include clear before/after images.
If the change depends on motion, timing, transitions, or interaction details, include a short video.
If we have to guess what changed, we are much less likely to review it.
## Issues First
If you are thinking about a non-trivial change, open an issue first.
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
## Be Realistic
Opening a PR does not create an obligation on our side.
We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later.
If you are fine with that, proceed.
+3 -1
View File
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
@@ -50,8 +51,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `commandPalette.toggle`: open or close the global command palette
- `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`)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 T3 Tools Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+37 -98
View File
@@ -1,124 +1,63 @@
# 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, Claude, and OpenCode, more coming soon).
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## Installation
## Architecture
> [!WARNING]
> T3 Code currently supports Codex, Claude, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
## Quick start
### Run without installing
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
## Scripts
### Desktop app
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
### Desktop `.dmg` packaging notes
#### Windows (`winget`)
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
```bash
winget install T3Tools.T3Code
```
### Running multiple dev instances
#### macOS (Homebrew)
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
```bash
brew install --cask t3-code
```
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
#### Arch Linux (AUR)
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
```bash
yay -S t3code-bin
```
## Runtime modes
## Some notes
T3 Code has a global runtime mode switch in the chat toolbar:
We are very very early in this project. Expect bugs.
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
We are not accepting contributions yet.
## Provider architecture
Observability guide: [docs/observability.md](./docs/observability.md)
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
## If you REALLY want to contribute still.... read this first
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Before local development, prepare the environment and install dependencies:
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
bun install .
```
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+175 -41
View File
@@ -1,65 +1,199 @@
# 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 default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
4. Use **Create Link** to generate a pairing link you can share with another device.
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
available. You can set another endpoint as the default from the expanded endpoint list.
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
automatically.
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
### Tailscale Endpoints
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
Depending on your Tailscale setup, this may include:
- the machine's `100.x.y.z` Tailnet IP
- a MagicDNS name
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
Serve to proxy HTTPS traffic to the local backend.
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
### 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
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
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.
## 2) Tailnet / Tailscale access
If you use Tailscale, you can bind directly to your Tailnet address.
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
```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
npx t3 serve --tailscale-serve
```
Open from any device in your tailnet:
By default this configures Tailscale Serve on HTTPS port 443 and advertises
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
`http://<tailnet-ip>:3773`
```bash
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
```
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
> 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.
### Option 3: Desktop-Managed SSH Launch
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
1. Open **Settings** → **Connections**.
2. Under **Remote Environments**, choose **Add environment**.
3. Select the SSH launch flow.
4. Enter the SSH target, such as `[email protected]`.
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
#### SSH Launch Troubleshooting
The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.
The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:
```text
^22.16 || ^23.11 || >=24.10
```
During SSH launch, T3 Code first checks whether `node` is already available on `PATH`. If it is missing, the launcher tries common non-interactive shell locations and version-manager shims/activation hooks:
- `~/.local/bin`, `~/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/bin`
- Volta via `~/.volta/bin`
- asdf via `~/.asdf/shims`, `~/.asdf/bin`, or `~/.asdf/asdf.sh`
- mise via `~/.local/share/mise/shims`, `~/.mise/shims`, or `mise activate sh`
- fnm via `fnm env --use-on-cd --shell sh` or `fnm env --shell sh`
- nodenv via `~/.nodenv/bin`, `~/.nodenv/shims`, or `nodenv init -`
- nvm via `$NVM_DIR/nvm.sh`, then `nvm use default`, `nvm use node`, or `nvm use --lts`
- installed nvm versions under `$NVM_DIR/versions/node/*/bin`
If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:
```bash
ssh [email protected] 'sh -lc "command -v node && node --version"'
```
If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:
```bash
nvm alias default 24
```
With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and points at a Node version satisfying the range above.
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
## How Pairing Works
The remote device does not need a long-lived secret up front.
Instead:
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.
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Hosted Web App Pairing
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
## 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.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
-582
View File
@@ -1,582 +0,0 @@
# Orchestration Interface Spec (Required State)
Status: Required target architecture (not a description of current behavior).
## 1. Identifier Schema (Branded)
All identifiers are branded and never plain `string` in schema definitions.
```ts
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
const EventId = Schema.String.pipe(Schema.brand("EventId"));
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
```
Rules:
- `ThreadId` is app/orchestration thread identity.
- `ProviderThreadId` is provider runtime thread identity.
- They are never assigned to each other.
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
## 2. Client Commands (Domain Commands)
All commands are sent through one RPC: `orchestration.dispatchCommand`.
Output for every command: `DispatchResultSchema = { sequence: number }`.
### 2.1 Client-Dispatchable Commands
1. `project.create`
- Input:
- `commandId: CommandId`
- `projectId: ProjectId`
- `title: string`
- `workspaceRoot: string`
- `defaultModel?: string`
- `createdAt: IsoDateTime`
- Output: `DispatchResult`
2. `project.meta.update`
- Input:
- `commandId: CommandId`
- `projectId: ProjectId`
- optional `{ title, workspaceRoot, defaultModel, scripts }`
- Output: `DispatchResult`
3. `project.delete`
- Input: `commandId`, `projectId`
- Output: `DispatchResult`
4. `thread.create`
- Input:
- `commandId: CommandId`
- `threadId: ThreadId`
- `projectId: ProjectId`
- `title: string`
- `model: string`
- `branch: string | null`
- `worktreePath: string | null`
- `createdAt: IsoDateTime`
- Output: `DispatchResult`
5. `thread.delete`
- Input: `commandId`, `threadId`
- Output: `DispatchResult`
6. `thread.meta.update`
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
- Output: `DispatchResult`
7. `thread.turn.start`
- Input:
- `commandId`
- `threadId`
- `message`:
- `messageId: MessageId`
- `role: "user"`
- `text: string`
- `attachments: ChatAttachment[]` (schema-shared)
- `model?: string`
- `effort?: string`
- `createdAt`
- Output: `DispatchResult`
8. `thread.turn.interrupt`
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
- Output: `DispatchResult`
9. `thread.approval.respond`
- Input:
- `commandId`
- `threadId`
- `requestId: ApprovalRequestId`
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
- `createdAt`
- Output: `DispatchResult`
10. `thread.checkpoint.revert`
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
- Output: `DispatchResult`
11. `thread.session.stop`
- Input: `commandId`, `threadId`, `createdAt`
- Output: `DispatchResult`
### 2.2 Internal-Only Commands (Not Client Dispatchable)
1. `thread.session.set`
- Server-owned projection update for session lifecycle.
2. `thread.message.assistant.delta`
- Server-owned incremental assistant content append.
3. `thread.message.assistant.complete`
- Server-owned assistant message completion marker.
4. `thread.turn.diff.complete`
- Server-owned checkpoint diff summary write.
5. `thread.activity.append`
- Server-owned activity feed append.
## 3. Client RPC (Required)
These are the required client-facing RPC methods.
1. `orchestration.getSnapshot`
- Input: `{}`
- Output: `OrchestrationReadModel`
2. `orchestration.dispatchCommand`
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
- Output: `DispatchResult`
3. `orchestration.getTurnDiff`
- Input:
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- Output:
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- `diff: string`
4. `orchestration.replayEvents` (optional operational/debug API)
- Input: `{ fromSequenceExclusive: number }`
- Output: `OrchestrationEvent[]`
### 3.1 RPC To Remove
Remove from client boundary:
- `providers.startSession`
- `providers.sendTurn`
- `providers.interruptTurn`
- `providers.respondToRequest`
- `providers.stopSession`
- `providers.listCheckpoints`
- `providers.getCheckpointDiff`
- `providers.revertToCheckpoint`
Rationale:
- Session/turn/checkpoint control belongs to orchestrator command path.
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
## 4. Server Orchestrator Command <-> Event Schemas
Each command deterministically yields one or more domain events that are persisted to the event store.
1. `project.create` -> `project.created`
2. `project.meta.update` -> `project.meta-updated`
3. `project.delete` -> `project.deleted`
4. `thread.create` -> `thread.created`
5. `thread.delete` -> `thread.deleted`
6. `thread.meta.update` -> `thread.meta-updated`
7. `thread.turn.start` ->
- `thread.message-sent` (user message append)
- `thread.turn-start-requested`
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
9. `thread.approval.respond` -> `thread.approval-response-requested`
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
Internal command/event path:
- `thread.session.set` -> `thread.session-set`
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
- `thread.activity.append` -> `thread.activity-appended`
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
Required mapping pipeline:
`Raw Provider Event (adapter-specific)`
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
-> `Internal Orchestration Command`
-> `Orchestration Domain Event`
### 5.1 Mapping Table for Codex Adapter
1. Raw `thread/started`
- Generic: `thread.started`
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
- Domain event: `thread.session-set`
2. Raw `turn/started`
- Generic: `turn.started`
- Internal command: `thread.session.set` (status `running`, active turn)
- Domain event: `thread.session-set`
3. Raw `item/agentMessage/delta`
- Generic: `message.delta`
- Internal command: `thread.message.assistant.delta`
- Domain event: `thread.message-sent` (assistant, streaming)
4. Raw `item/completed` (agent message)
- Generic: `message.completed`
- Internal command: `thread.message.assistant.complete`
- Domain event: `thread.message-sent` (assistant, completed)
5. Raw `turn/completed`
- Generic: `turn.completed`
- Internal commands:
- `thread.session.set` (ready/error)
- `thread.activity.append` (optional summary)
- Domain events: `thread.session-set`, `thread.activity-appended`
6. Raw approval request
- Generic: `approval.requested`
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
- Domain event: `thread.activity-appended`
7. Raw approval decision ack
- Generic: `approval.resolved`
- Internal command: `thread.activity.append`
- Domain event: `thread.activity-appended`
8. Raw tool start/complete
- Generic: `tool.started` / `tool.completed`
- Internal command: `thread.activity.append`
- Domain event: `thread.activity-appended`
9. Checkpoint capture (server-produced)
- Generic: `checkpoint.captured`
- Internal command: `thread.turn.diff.complete`
- Domain event: `thread.turn-diff-completed`
10. Raw/runtime error
- Generic: `runtime.error`
- Internal commands:
- `thread.session.set` (status `error`)
- `thread.activity.append` (`tone=error`)
- Domain events: `thread.session-set`, `thread.activity-appended`
## 6. Schema Section (Boundary + Reuse)
### 6.1 Shared Schemas (contracts package)
Expose to both web and server:
- `OrchestrationReadModelSchema`
- `ClientOrchestrationCommandSchema`
- `OrchestrationEventSchema`
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
- Shared message/activity/checkpoint summary schemas used in snapshot
### 6.2 Server-Internal Schemas
Not exposed to web:
- `InternalOrchestrationCommandSchema`
- Adapter raw-event schemas and provider-specific payload schemas
- Provider session directory records and persistence-only row schemas
- Git service cache/query schemas (non-orchestration read model)
### 6.3 Reuse Requirements
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
## 7. Persistence Model (Required)
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
### 7.1 Write-Side Persisted Tables
1. `orchestration_events` (append-only event store)
- `sequence: number` (global monotonic sequence, primary key)
- `eventId: EventId` (unique)
- `aggregateKind: "project" | "thread"`
- `streamId: ProjectId | ThreadId` (aggregate stream id)
- `streamVersion: number` (per-aggregate monotonic version)
- `eventType: OrchestrationEventType`
- `occurredAt: IsoDateTime`
- `commandId: CommandId | null`
- `causationEventId: EventId | null`
- `correlationId: CommandId | null`
- `actorKind: "client" | "server" | "provider"`
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
- `metadata: OrchestrationEventMetadata`
2. `orchestration_command_receipts` (idempotency + ack replay)
- `commandId: CommandId` (primary key)
- `aggregateKind: "project" | "thread"`
- `aggregateId: ProjectId | ThreadId`
- `acceptedAt: IsoDateTime`
- `resultSequence: number`
- `status: "accepted" | "rejected"`
- `error: string | null`
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
- `threadId: ThreadId`
- `fromTurnCount: number`
- `toTurnCount: number`
- `diff: string`
- `createdAt: IsoDateTime`
- unique key: `(threadId, fromTurnCount, toTurnCount)`
4. `provider_session_runtime` (server-internal adapter resume state)
- `providerSessionId: ProviderSessionId` (primary key)
- `threadId: ThreadId`
- `providerName: string`
- `adapterKey: string`
- `providerThreadId: ProviderThreadId | null`
- `status: "starting" | "running" | "stopped" | "error"`
- `lastSeenAt: IsoDateTime`
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
### 7.2 Canonical Persisted Event Schema
`OrchestrationPersistedEventSchema` (full envelope):
```ts
type OrchestrationPersistedEvent = {
sequence: number;
eventId: EventId;
aggregateKind: "project" | "thread";
streamId: ProjectId | ThreadId;
streamVersion: number;
eventType: OrchestrationEventType;
occurredAt: IsoDateTime;
commandId: CommandId | null;
causationEventId: EventId | null;
correlationId: CommandId | null;
actorKind: "client" | "server" | "provider";
payload: OrchestrationEventPayload;
metadata: {
providerSessionId?: ProviderSessionId;
providerThreadId?: ProviderThreadId;
providerTurnId?: ProviderTurnId;
providerItemId?: ProviderItemId;
adapterKey?: string;
requestId?: ApprovalRequestId;
ingestedAt?: IsoDateTime;
};
};
```
Rules:
- `payload` must be schema-discriminated by `eventType`.
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
- `streamVersion` is concurrency guard for aggregate writes.
### 7.3 Required Projected Tables (Read Models)
1. `projection_projects`
- `projectId: ProjectId` (primary key)
- `title: string`
- `workspaceRoot: string`
- `defaultModel: string | null`
- `scripts: ProjectScript[]`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
- `deletedAt: IsoDateTime | null`
2. `projection_threads`
- `threadId: ThreadId` (primary key)
- `projectId: ProjectId`
- `title: string`
- `model: string`
- `branch: string | null`
- `worktreePath: string | null`
- `latestTurnId: TurnId | null`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
- `deletedAt: IsoDateTime | null`
3. `projection_thread_messages`
- `messageId: MessageId` (primary key)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `role: "user" | "assistant" | "system"`
- `text: string`
- `isStreaming: boolean`
- `createdAt: IsoDateTime`
- `updatedAt: IsoDateTime`
4. `projection_thread_activities`
- `activityId: EventId` (primary key; derived from source event)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `tone: "info" | "tool" | "approval" | "error"`
- `kind: string`
- `summary: string`
- `payload: JsonValue`
- `createdAt: IsoDateTime`
5. `projection_thread_sessions`
- `threadId: ThreadId` (primary key)
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
- `providerName: string | null`
- `providerSessionId: ProviderSessionId | null`
- `providerThreadId: ProviderThreadId | null`
- `activeTurnId: TurnId | null`
- `lastError: string | null`
- `updatedAt: IsoDateTime`
6. `projection_thread_turns`
- `turnId: TurnId` (primary key)
- `threadId: ThreadId`
- `turnCount: number`
- `status: "running" | "completed" | "interrupted" | "error"`
- `userMessageId: MessageId | null`
- `assistantMessageId: MessageId | null`
- `startedAt: IsoDateTime`
- `completedAt: IsoDateTime | null`
7. `projection_checkpoints`
- `threadId: ThreadId`
- `turnId: TurnId`
- `checkpointTurnCount: number`
- `checkpointRef: CheckpointRef`
- `status: "ready" | "missing" | "error"`
- `files: JsonArray` (typed as file diff summary schema)
- `assistantMessageId: MessageId | null`
- `completedAt: IsoDateTime`
- unique key: `(threadId, checkpointTurnCount)`
8. `projection_pending_approvals`
- `requestId: ApprovalRequestId` (primary key)
- `threadId: ThreadId`
- `turnId: TurnId | null`
- `status: "pending" | "resolved"`
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
- `createdAt: IsoDateTime`
- `resolvedAt: IsoDateTime | null`
9. `projection_state`
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
- `lastAppliedSequence: number`
- `updatedAt: IsoDateTime`
Projection consistency rules:
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
### 7.4 Snapshot and RPC Requirements
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
2. Snapshot must include `projects[]` from `projection_projects`.
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
- `turnId: TurnId`
- `completedAt: IsoDateTime`
- `status`
- `files[]` (`path`, `kind`, `additions`, `deletions`)
- `checkpointRef: CheckpointRef`
- `assistantMessageId?: MessageId`
- `checkpointTurnCount: number`
4. Client does not require `listCheckpoints` RPC:
- checkpoint list comes from snapshot projections
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
5. Provider session identity is not a client routing key:
- client acts on `ThreadId`
- server resolves provider session internally via `projection_thread_sessions`
6. `snapshotSequence` is derived from `projection_state`:
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
7. Event subscription handoff contract:
- client performs `getSnapshot` and reads `snapshotSequence`
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
### 7.5 External Derived State (Non-Orchestration)
1. Current git/worktree state is not projected from orchestration events.
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
### 7.6 Existing Repository Placement
1. `ProjectsRepository`
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
- Must not bypass command->event append path for mutations.
2. `CheckpointsRepository`
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
- Must not be an independent source of truth outside orchestration events.
3. `ProviderSessionsRepository`
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
- Not part of client RPC/domain aggregate boundary.
-12
View File
@@ -2,24 +2,12 @@
## Small things
- [ ] Plan mode
- [ ] Submitting new messages should scroll to bottom
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
- [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [x] Insta focus input on new thread creation
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things
- [ ] Queueing messages
- [x] External runners (i.e. running the cli on a mac mini)
-2
View File
@@ -1,2 +0,0 @@
dist-electron/
.electron-runtime/
+19 -12
View File
@@ -1,29 +1,36 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.24",
"private": true,
"main": "dist-electron/main.js",
"type": "module",
"main": "dist-electron/main.cjs",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "40.6.0"
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"wait-on": "^8.0.2"
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+186 -31
View File
@@ -1,43 +1,189 @@
import { spawnSync } from "node:child_process";
import electronmon from "electronmon";
import waitOn from "wait-on";
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
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 devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
if (!devServerUrl) {
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
}
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
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.cjs",
"dist-electron/preload.cjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpHost: devServer.hostname,
tcpPort: port,
});
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
let shuttingDown = false;
let restartTimer = null;
let currentApp = null;
let restartQueue = Promise.resolve();
const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
if (process.platform === "win32") {
return;
}
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
}
function startApp() {
if (shuttingDown || currentApp !== null) {
return;
}
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
{
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
},
);
currentApp = app;
app.once("error", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown) {
scheduleRestart();
}
});
app.once("exit", (code, signal) => {
if (currentApp === app) {
currentApp = null;
}
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
scheduleRestart();
}
});
}
async function stopApp() {
const app = currentApp;
if (!app) {
return;
}
currentApp = null;
expectedExits.add(app);
await new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) {
return;
}
settled = true;
resolve();
};
app.once("exit", finish);
app.kill("SIGTERM");
killChildTreeByPid(app.pid, "TERM");
setTimeout(() => {
if (settled) {
return;
}
app.kill("SIGKILL");
killChildTreeByPid(app.pid, "KILL");
finish();
}, forcedShutdownTimeoutMs).unref();
});
}
function scheduleRestart() {
if (shuttingDown) {
return;
}
if (restartTimer) {
clearTimeout(restartTimer);
}
restartTimer = setTimeout(() => {
restartTimer = null;
restartQueue = restartQueue
.catch(() => undefined)
.then(async () => {
await stopApp();
if (!shuttingDown) {
startApp();
}
});
}, restartDebounceMs);
}
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;
}
scheduleRestart();
},
);
watchers.push(watcher);
}
}
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
@@ -45,20 +191,29 @@ async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
for (const watcher of watchers) {
watcher.close();
}
await stopApp();
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
await new Promise((resolve) => {
setTimeout(resolve, childTreeGracePeriodMs);
});
killChildTree("KILL");
process.exit(exitCode);
}
startWatchers();
cleanupStaleDevApps();
startApp();
process.once("SIGINT", () => {
void shutdown(130);
});
+75 -39
View File
@@ -6,8 +6,8 @@ import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
@@ -18,11 +18,14 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 2;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
@@ -43,6 +46,68 @@ function setPlistString(plistPath, key, value) {
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
runChecked("sips", [
"-z",
String(size),
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
runChecked("sips", [
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
@@ -55,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
@@ -102,7 +133,7 @@ function buildMacLauncher(electronBinaryPath) {
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = join(desktopDir, "resources", "icon.icns");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
@@ -126,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
@@ -140,5 +170,11 @@ export function resolveElectronPath() {
return electronBinaryPath;
}
// Dev launches do not need a renamed app bundle badly enough to risk breaking
// Electron helper resource lookup on macOS.
if (isDevelopment) {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
+1 -1
View File
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+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);
}
}
+240
View File
@@ -0,0 +1,240 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as NetService from "@t3tools/shared/Net";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
const makeDesktopRunId = Random.nextUUIDv4.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
class DesktopBackendPortUnavailableError extends Data.TaggedError(
"DesktopBackendPortUnavailableError",
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
"DesktopDevelopmentBackendPortRequiredError",
)<{}> {
override get message() {
return "T3CODE_PORT is required in desktop development.";
}
}
const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
DesktopObservability.makeComponentLogger("desktop-bootstrap");
const { logInfo: logStartupInfo, logError: logStartupError } =
DesktopObservability.makeComponentLogger("desktop-startup");
const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
configuredPort: Option.Option<number>,
) {
if (Option.isSome(configuredPort)) {
return {
port: configuredPort.value,
selectedByScan: false,
} as const;
}
const net = yield* NetService.NetService;
for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
let availableOnEveryHost = true;
for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
if (!(yield* net.canListenOnHost(port, host))) {
availableOnEveryHost = false;
break;
}
}
if (availableOnEveryHost) {
return {
port,
selectedByScan: true,
} as const;
}
}
return yield* new DesktopBackendPortUnavailableError({
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
maxPort: MAX_TCP_PORT,
hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
});
});
const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
stage: string,
error: unknown,
): Effect.fn.Return<
void,
never,
| DesktopLifecycle.DesktopShutdown
| DesktopState.DesktopState
| ElectronApp.ElectronApp
| ElectronDialog.ElectronDialog
> {
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const state = yield* DesktopState.DesktopState;
const electronApp = yield* ElectronApp.ElectronApp;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const message = error instanceof Error ? error.message : String(error);
const detail =
error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
yield* logStartupError("fatal startup error", {
stage,
message,
...(detail.length > 0 ? { detail } : {}),
});
const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
if (!wasQuitting) {
yield* electronDialog.showErrorBox(
"T3 Code failed to start",
`Stage: ${stage}\n${message}${detail}`,
);
}
yield* shutdown.request;
yield* electronApp.quit;
});
const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
const bootstrap = Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* logBootstrapInfo("bootstrap start");
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
return yield* new DesktopDevelopmentBackendPortRequiredError();
}
const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
const backendPort = backendPortSelection.port;
yield* logBootstrapInfo(
backendPortSelection.selectedByScan
? "selected backend port via sequential scan"
: "using configured backend port",
{
port: backendPort,
...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
},
);
const settings = yield* desktopSettings.get;
if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
mode: settings.serverExposureMode,
});
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig;
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
if (serverExposureState.endpointUrl) {
yield* logBootstrapInfo("bootstrap enabled network access", {
endpointUrl: serverExposureState.endpointUrl,
});
} else if (settings.serverExposureMode === "network-accessible") {
yield* logBootstrapWarning(
"bootstrap fell back to local-only because no advertised network host was available",
);
}
yield* installDesktopIpcHandlers;
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
yield* backendManager.start;
yield* logBootstrapInfo("bootstrap backend start requested");
}
}).pipe(Effect.withSpan("desktop.bootstrap"));
const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* shellEnvironment.installIntoProcess;
const userDataPath = yield* appIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
}
yield* appIdentity.configure;
yield* lifecycle.register;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
);
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
const scopedProgram = Effect.scoped(
Effect.gen(function* () {
const runId = yield* makeDesktopRunId;
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
);
yield* startup;
yield* shutdown.awaitRequest;
}),
);
export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));
@@ -0,0 +1,176 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const defaultEnvironmentInput = {
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
type TestEnvironmentInput = Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> & {
readonly env?: Record<string, string | undefined>;
};
interface ElectronAppCalls {
readonly setAboutPanelOptions: Array<Electron.AboutPanelOptionsOptions>;
readonly setDockIcon: string[];
readonly setName: string[];
}
const makeElectronAppLayer = (calls: ElectronAppCalls) =>
Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: (name) =>
Effect.sync(() => {
calls.setName.push(name);
}),
setAboutPanelOptions: (options) =>
Effect.sync(() => {
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
setDesktopName: () => Effect.void,
setDockIcon: (iconPath) =>
Effect.sync(() => {
calls.setDockIcon.push(iconPath);
}),
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronAppShape);
const makeAssetsLayer = (png: Option.Option<string>) =>
Layer.succeed(DesktopAssets.DesktopAssets, {
iconPaths: Effect.succeed({
ico: Option.none(),
icns: Option.none(),
png,
}),
resolveResourcePath: () => Effect.succeed(Option.none()),
} satisfies DesktopAssets.DesktopAssetsShape);
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
const { env, ...environmentOverrides } = overrides;
return DesktopEnvironment.layer({
...defaultEnvironmentInput,
...environmentOverrides,
}).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
...env,
}),
),
),
);
};
const withIdentity = <A, E, R>(
effect: Effect.Effect<
A,
E,
| R
| DesktopAppIdentity.DesktopAppIdentity
| DesktopEnvironment.DesktopEnvironment
| FileSystem.FileSystem
>,
input: {
readonly calls?: ElectronAppCalls;
readonly environment?: TestEnvironmentInput;
readonly legacyPathExists?: boolean;
readonly packageJson?: string;
readonly pngIconPath?: Option.Option<string>;
} = {},
) => {
const calls: ElectronAppCalls = input.calls ?? {
setAboutPanelOptions: [],
setDockIcon: [],
setName: [],
};
return effect.pipe(
Effect.provide(
DesktopAppIdentity.layer.pipe(
Layer.provideMerge(
FileSystem.layerNoop({
exists: (path) =>
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}),
),
Layer.provideMerge(makeAssetsLayer(input.pngIconPath ?? Option.none())),
Layer.provideMerge(makeElectronAppLayer(calls)),
Layer.provideMerge(makeEnvironmentLayer(input.environment)),
),
),
);
};
describe("DesktopAppIdentity", () => {
it.effect("keeps using the legacy userData path when it already exists", () =>
withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const userDataPath = yield* identity.resolveUserDataPath;
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)");
}),
{ legacyPathExists: true },
),
);
it.effect("configures app identity from the environment commit override", () => {
const calls: ElectronAppCalls = {
setAboutPanelOptions: [],
setDockIcon: [],
setName: [],
};
return withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
yield* identity.configure;
assert.deepEqual(calls.setName, ["T3 Code (Alpha)"]);
assert.equal(calls.setAboutPanelOptions[0]?.applicationName, "T3 Code (Alpha)");
assert.equal(calls.setAboutPanelOptions[0]?.applicationVersion, "1.2.3");
assert.equal(calls.setAboutPanelOptions[0]?.version, "0123456789ab");
assert.deepEqual(calls.setDockIcon, ["/icon.png"]);
}),
{
calls,
environment: {
env: {
T3CODE_COMMIT_HASH: "0123456789abcdef",
},
},
pngIconPath: Option.some("/icon.png"),
},
);
});
});
+128
View File
@@ -0,0 +1,128 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
const AppPackageMetadata = Schema.Struct({
t3codeCommitHash: Schema.optional(Schema.String),
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
DesktopAppIdentityShape
>()("t3/desktop/AppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
const trimmed = value.trim();
return COMMIT_HASH_PATTERN.test(trimmed)
? Option.some(trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase())
: Option.none();
};
const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const commitHashCache = yield* Ref.make<Option.Option<Option.Option<string>>>(Option.none());
const resolveEmbeddedCommitHash = Effect.gen(function* () {
const packageJsonPath = environment.path.join(environment.appRoot, "package.json");
const raw = yield* fileSystem.readFileString(packageJsonPath).pipe(Effect.option);
return yield* Option.match(raw, {
onNone: () => Effect.succeed(Option.none<string>()),
onSome: (value) =>
decodeAppPackageMetadata(value).pipe(
Effect.map((parsed) =>
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
),
Effect.catch(() => Effect.succeed(Option.none<string>())),
),
});
});
const resolveAboutCommitHash = Effect.gen(function* () {
const cached = yield* Ref.get(commitHashCache);
if (Option.isSome(cached)) {
return cached.value;
}
const override = Option.flatMap(environment.commitHashOverride, normalizeCommitHash);
if (Option.isSome(override)) {
yield* Ref.set(commitHashCache, Option.some(override));
return override;
}
if (!environment.isPackaged) {
const empty = Option.none<string>();
yield* Ref.set(commitHashCache, Option.some(empty));
return empty;
}
const commitHash = yield* resolveEmbeddedCommitHash;
yield* Ref.set(commitHashCache, Option.some(commitHash));
return commitHash;
});
const resolveUserDataPath = Effect.gen(function* () {
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem
.exists(legacyPath)
.pipe(Effect.orElseSucceed(() => false));
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
const configure = Effect.gen(function* () {
const commitHash = yield* resolveAboutCommitHash;
yield* electronApp.setName(environment.displayName);
yield* electronApp.setAboutPanelOptions({
applicationName: environment.displayName,
applicationVersion: environment.appVersion,
version: Option.getOrElse(commitHash, () => "unknown"),
});
if (environment.platform === "win32") {
yield* electronApp.setAppUserModelId(environment.appUserModelId);
}
if (environment.platform === "linux") {
yield* electronApp.setDesktopName(environment.linuxDesktopEntryName);
}
if (environment.platform === "darwin") {
const iconPaths = yield* assets.iconPaths;
yield* Option.match(iconPaths.png, {
onNone: () => Effect.void,
onSome: electronApp.setDockIcon,
});
}
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
return DesktopAppIdentity.of({
resolveUserDataPath,
configure,
});
});
export const layer = Layer.effect(DesktopAppIdentity, make);
+85
View File
@@ -0,0 +1,85 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
export interface DesktopIconPaths {
readonly ico: Option.Option<string>;
readonly icns: Option.Option<string>;
readonly png: Option.Option<string>;
}
export interface DesktopAssetsShape {
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"t3/desktop/Assets",
) {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
fileName: string,
): Effect.fn.Return<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const candidates = environment.resolveResourcePathCandidates(fileName);
for (const candidate of candidates) {
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (exists) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
.pipe(Effect.orElseSucceed(() => false));
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
}
}
return yield* resolveResourcePath(`icon.${ext}`);
});
const make = Effect.gen(function* () {
const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>();
const [ico, icns, png] = yield* Effect.all(
[resolveIconPath("ico"), resolveIconPath("icns"), resolveIconPath("png")] as const,
{ concurrency: "unbounded" },
);
const iconPaths = { ico, icns, png } satisfies DesktopIconPaths;
return DesktopAssets.of({
iconPaths: Effect.succeed(iconPaths),
resolveResourcePath: Effect.fn("desktop.assets.resolveResourcePath.scoped")(
function* (fileName) {
return yield* resolveResourcePath(fileName).pipe(Effect.provide(context));
},
),
});
});
export const layer = Layer.effect(DesktopAssets, make);
+58
View File
@@ -0,0 +1,58 @@
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Option from "effect/Option";
const trimNonEmptyOption = (value: string): Option.Option<string> => {
const trimmed = value.trim();
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
};
const trimmedString = (name: string) =>
Config.string(name).pipe(Config.option, Config.map(Option.flatMap(trimNonEmptyOption)));
const optionalBoolean = (name: string) =>
Config.boolean(name).pipe(Config.option, Config.map(Option.getOrElse(() => false)));
const commaSeparatedStrings = (name: string) =>
trimmedString(name).pipe(
Config.map(
Option.match({
onNone: () => [],
onSome: (value) =>
value
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
}),
),
);
const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<string, string> =>
Object.fromEntries(
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
);
export const DesktopConfig = Config.all({
appDataDirectory: trimmedString("APPDATA"),
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
devRemoteT3ServerEntryPath: trimmedString("T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH"),
configuredBackendPort: Config.port("T3CODE_PORT").pipe(Config.option),
commitHashOverride: trimmedString("T3CODE_COMMIT_HASH"),
desktopLanHostOverride: trimmedString("T3CODE_DESKTOP_LAN_HOST"),
desktopHttpsEndpointUrls: commaSeparatedStrings("T3CODE_DESKTOP_HTTPS_ENDPOINTS"),
otlpTracesUrl: trimmedString("T3CODE_OTLP_TRACES_URL"),
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
appImagePath: trimmedString("APPIMAGE"),
disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"),
mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"),
mockUpdateServerPort: Config.port("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(
Config.withDefault(3000),
),
});
export const layerTest = (env: Readonly<Record<string, string | undefined>>) =>
ConfigProvider.layer(ConfigProvider.fromEnv({ env: compactEnv(env) }));
@@ -0,0 +1,117 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
const defaultInput = {
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "0.0.22",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: false,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeEnvironmentLayer = (
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
env: Record<string, string | undefined> = {},
) =>
DesktopEnvironment.layer({
...defaultInput,
...overrides,
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest(env))));
const makeEnvironment = (
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
env: Record<string, string | undefined> = {},
) =>
Effect.gen(function* () {
return yield* DesktopEnvironment.DesktopEnvironment;
}).pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
describe("DesktopEnvironment", () => {
it.effect("derives state paths and development identity inside Effect", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
{
T3CODE_HOME: " /tmp/t3 ",
T3CODE_COMMIT_HASH: " 0123456789abcdef ",
T3CODE_PORT: "4949",
VITE_DEV_SERVER_URL: "http://localhost:5173",
T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH: " /remote/server.mjs ",
T3CODE_OTLP_TRACES_URL: " http://127.0.0.1:4318/v1/traces ",
T3CODE_OTLP_EXPORT_INTERVAL_MS: "2500",
},
);
assert.equal(environment.isDevelopment, true);
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
assert.equal(environment.baseDir, "/tmp/t3");
assert.equal(environment.stateDir, "/tmp/t3/dev");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
assert.equal(environment.backendCwd, "/repo");
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
assert.equal(environment.linuxWmClass, "t3code-dev");
assert.deepEqual(
Option.map(environment.devServerUrl, (url) => url.href),
Option.some("http://localhost:5173/"),
);
assert.deepEqual(environment.devRemoteT3ServerEntryPath, Option.some("/remote/server.mjs"));
assert.deepEqual(environment.configuredBackendPort, Option.some(4949));
assert.deepEqual(environment.commitHashOverride, Option.some("0123456789abcdef"));
assert.deepEqual(environment.otlpTracesUrl, Option.some("http://127.0.0.1:4318/v1/traces"));
assert.equal(environment.otlpExportIntervalMs, 2500);
}),
);
it.effect("derives production state paths under userdata", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
{
T3CODE_HOME: "/tmp/t3",
},
);
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
}),
);
it.effect("resolves picker defaults without nullish sentinels", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment();
assert.deepEqual(environment.resolvePickFolderDefaultPath(null), Option.none());
assert.deepEqual(
environment.resolvePickFolderDefaultPath({ initialPath: " " }),
Option.none(),
);
assert.deepEqual(
environment.resolvePickFolderDefaultPath({ initialPath: "~" }),
Option.some("/Users/alice"),
);
assert.deepEqual(
environment.resolvePickFolderDefaultPath({ initialPath: "~/project" }),
Option.some("/Users/alice/project"),
);
}),
);
});
+249
View File
@@ -0,0 +1,249 @@
import type {
DesktopAppBranding,
DesktopAppStageLabel,
DesktopRuntimeArch,
DesktopRuntimeInfo,
} from "@t3tools/contracts";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import {
type DesktopSettings,
resolveDefaultDesktopSettings,
} from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
export interface MakeDesktopEnvironmentInput {
readonly dirname: string;
readonly homeDirectory: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly appVersion: string;
readonly appPath: string;
readonly isPackaged: boolean;
readonly resourcesPath: string;
readonly runningUnderArm64Translation: boolean;
}
export interface DesktopEnvironmentShape {
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
DesktopEnvironmentShape
>()("t3/desktop/Environment") {}
const APP_BASE_NAME = "T3 Code";
function resolveDesktopAppStageLabel(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppStageLabel {
if (input.isDevelopment) {
return "Dev";
}
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
const stageLabel = resolveDesktopAppStageLabel(input);
return {
baseName: APP_BASE_NAME,
stageLabel,
displayName: `${APP_BASE_NAME} (${stageLabel})`,
};
}
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
return "other";
}
function resolveDesktopRuntimeInfo(input: {
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly runningUnderArm64Translation: boolean;
}): DesktopRuntimeInfo {
const appArch = normalizeDesktopArch(input.processArch);
if (input.platform !== "darwin") {
return {
hostArch: appArch,
appArch,
runningUnderArm64Translation: false,
};
}
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
appArch,
runningUnderArm64Translation: input.runningUnderArm64Translation,
};
}
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
input: MakeDesktopEnvironmentInput,
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
const path = yield* Path.Path;
const config = yield* DesktopConfig.DesktopConfig;
const homeDirectory = input.homeDirectory;
const devServerUrl = config.devServerUrl;
const isDevelopment = Option.isSome(devServerUrl);
const appDataDirectory =
input.platform === "win32"
? Option.getOrElse(config.appDataDirectory, () =>
path.join(homeDirectory, "AppData", "Roaming"),
)
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
isDevelopment,
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
path,
dirname: input.dirname,
platform: input.platform,
processArch: input.processArch,
isPackaged: input.isPackaged,
isDevelopment,
appVersion: input.appVersion,
appPath: input.appPath,
resourcesPath,
homeDirectory,
appDataDirectory,
baseDir,
stateDir,
desktopSettingsPath: path.join(stateDir, "desktop-settings.json"),
clientSettingsPath: path.join(stateDir, "client-settings.json"),
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
serverSettingsPath: path.join(stateDir, "settings.json"),
logDir: path.join(stateDir, "logs"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
backendCwd: input.isPackaged ? homeDirectory : appRoot,
preloadPath: path.join(input.dirname, "preload.cjs"),
appUpdateYmlPath: input.isPackaged
? path.join(resourcesPath, "app-update.yml")
: path.join(input.appPath, "dev-app-update.yml"),
devServerUrl,
devRemoteT3ServerEntryPath: config.devRemoteT3ServerEntryPath,
configuredBackendPort: config.configuredBackendPort,
commitHashOverride: config.commitHashOverride,
otlpTracesUrl: config.otlpTracesUrl,
otlpExportIntervalMs: config.otlpExportIntervalMs,
branding,
displayName,
appUserModelId: isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
runtimeInfo: resolveDesktopRuntimeInfo({
platform: input.platform,
processArch: input.processArch,
runningUnderArm64Translation: input.runningUnderArm64Translation,
}),
resolvePickFolderDefaultPath: (rawOptions) => {
if (typeof rawOptions !== "object" || rawOptions === null) {
return Option.none();
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return Option.none();
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return Option.none();
}
if (trimmedPath === "~") {
return Option.some(homeDirectory);
}
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
return Option.some(path.join(homeDirectory, trimmedPath.slice(2)));
}
return Option.some(path.resolve(trimmedPath));
},
resolveResourcePathCandidates: (fileName) => [
path.join(input.dirname, "../resources", fileName),
path.join(input.dirname, "../prod-resources", fileName),
path.join(resourcesPath, "resources", fileName),
path.join(resourcesPath, fileName),
],
developmentDockIconPath: path.join(rootDir, "assets", "dev", "blueprint-macos-1024.png"),
});
});
export const layer = (input: MakeDesktopEnvironmentInput) =>
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
+233
View File
@@ -0,0 +1,233 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
export interface DesktopShutdownShape {
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"t3/desktop/Shutdown",
) {}
const makeShutdown = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown
| DesktopState.DesktopState
| DesktopWindow.DesktopWindow
| ElectronApp.ElectronApp
| ElectronTheme.ElectronTheme;
export interface DesktopLifecycleShape {
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"t3/desktop/Lifecycle",
) {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
DesktopObservability.makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown,
eventName: string,
listener: (...args: Args) => void,
): Effect.Effect<void, never, Scope.Scope> {
const eventTarget = target as {
on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
};
const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
return Effect.acquireRelease(
Effect.sync(() => {
eventTarget.on(eventName, untypedListener);
}),
() =>
Effect.sync(() => {
eventTarget.removeListener(eventName, untypedListener);
}),
).pipe(Effect.asVoid);
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
const shutdown = yield* DesktopShutdown;
yield* shutdown.request;
yield* shutdown.awaitComplete;
},
);
function handleBeforeQuit(
event: Electron.Event,
runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
allowQuit: () => boolean,
markQuitAllowed: () => void,
): void {
if (allowQuit()) {
void runEffect(
Effect.gen(function* () {
const state = yield* DesktopState.DesktopState;
yield* Ref.set(state.quitting, true);
yield* logLifecycleInfo("before-quit received");
}).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
);
return;
}
event.preventDefault();
void runEffect(
Effect.gen(function* () {
const state = yield* DesktopState.DesktopState;
yield* Ref.set(state.quitting, true);
yield* logLifecycleInfo("before-quit received");
yield* requestDesktopShutdownAndWait();
}).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
).finally(() => {
markQuitAllowed();
void runEffect(
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.quit;
}).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
);
});
}
function quitFromSignal(
signal: "SIGINT" | "SIGTERM",
runEffect: <A, E>(effect: Effect.Effect<A, E, DesktopLifecycleRuntimeServices>) => Promise<A>,
): void {
void runEffect(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ signal });
const electronApp = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
if (wasQuitting) return;
yield* logLifecycleInfo("process signal received", { signal });
yield* requestDesktopShutdownAndWait();
yield* electronApp.quit;
}).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
);
}
export const layer = Layer.succeed(
DesktopLifecycle,
DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
}),
);
@@ -0,0 +1,162 @@
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const decodeDesktopBackendChildLogRecord = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const TraceRecordLine = Schema.Struct({
name: Schema.String,
attributes: Schema.Record(Schema.String, Schema.Unknown),
events: Schema.Array(
Schema.Struct({
name: Schema.String,
attributes: Schema.Record(Schema.String, Schema.Unknown),
}),
),
});
const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
const environmentInput = (baseDir: string) =>
({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: false,
resourcesPath: "/repo/resources",
runningUnderArm64Translation: false,
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeEnvironmentLayer = (baseDir: string) =>
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
}),
),
),
);
describe("DesktopObservability", () => {
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-observability-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir);
const tracePath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
}).pipe(Effect.provide(environmentLayer));
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "desktop-main.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.scoped(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ "desktop.test": true });
yield* Effect.logInfo("desktop trace event");
}).pipe(
Effect.withSpan("desktop-observability-test"),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const records = (yield* fileSystem.readFileString(tracePath))
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => decodeTraceRecordLine(line));
const record = records.find((entry) => entry.name === "desktop-observability-test");
assert.notEqual(record, undefined);
if (!record) {
return;
}
assert.equal(record.attributes["desktop.test"], true);
assert.equal(
record.events.some((event) => event.name === "desktop trace event"),
true,
);
assert.isFalse(yield* fileSystem.exists(logPath));
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("persists backend child output as structured JSON records in development", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-log-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
});
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
);
const log = yield* fileSystem.readFileString(logPath);
const lines = log.trimEnd().split("\n");
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
assert.equal(boundary.message, "backend child process session start");
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(output.message, "backend child process output");
assert.equal(output.level, "INFO");
assert.equal(output.annotations.component, "desktop-backend-child");
assert.equal(output.annotations.runId, "test-run");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
});
@@ -0,0 +1,395 @@
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export interface DesktopBackendOutputLogShape {
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("t3/desktop/BackendOutputLog") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export type DesktopLogAnnotations = Record<string, unknown>;
export interface DesktopComponentLogger {
readonly annotate: <A, E, R>(
effect: Effect.Effect<A, E, R>,
annotations?: DesktopLogAnnotations,
) => Effect.Effect<A, E, R>;
readonly logDebug: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
readonly logInfo: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
readonly logWarning: (
message: string,
annotations?: DesktopLogAnnotations,
) => Effect.Effect<void>;
readonly logError: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
}
export function makeComponentLogger(component: string): DesktopComponentLogger {
const annotate: DesktopComponentLogger["annotate"] = (effect, annotations) =>
effect.pipe(
Effect.annotateLogs({
component,
...annotations,
}),
);
return {
annotate,
logDebug: (message, annotations) => annotate(Effect.logDebug(message), annotations),
logInfo: (message, annotations) => annotate(Effect.logInfo(message), annotations),
logWarning: (message, annotations) => annotate(Effect.logWarning(message), annotations),
logError: (message, annotations) => annotate(Effect.logError(message), annotations),
};
}
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
"DesktopLogFileWriterConfigurationError",
)<{
readonly option: "maxBytes" | "maxFiles";
readonly value: number;
}> {
override get message() {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes?: number;
readonly maxFiles?: number;
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
const baseName = path.basename(input.filePath);
if (maxBytes < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxBytes",
value: maxBytes,
});
}
if (maxFiles < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxFiles",
value: maxFiles,
});
}
yield* fileSystem.makeDirectory(directory, { recursive: true });
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
yield* pruneOverflowBackups;
return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const readPersistedOtlpTracesUrl: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
if (Option.isNone(raw)) {
return Option.none();
}
const parsed = parsePersistedServerObservabilitySettings(raw.value);
return Option.fromNullishOr(parsed.otlpTracesUrl);
});
const resolveOtlpTracesUrl = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (Option.isSome(environment.otlpTracesUrl)) {
return environment.otlpTracesUrl;
}
return yield* readPersistedOtlpTracesUrl;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
logFile: RotatingLogFileWriter,
input: {
readonly message: string;
readonly level: "INFO" | "ERROR";
readonly annotations: Record<string, unknown>;
},
): Effect.fn.Return<void> {
return yield* Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
const encoded = yield* encodeDesktopBackendChildLogRecord({
message: input.message,
level: input.level,
timestamp,
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
const backendOutputLogLayer = Layer.effect(
DesktopBackendOutputLog,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
return Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn(
"desktop.observability.backendOutput.writeSessionBoundary",
)(function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
phase,
details: sanitizeLogValue(details),
},
});
}),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
});
}),
);
const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
);
const tracerLayer = Layer.unwrap(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const otlpTracesUrl = yield* resolveOtlpTracesUrl;
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
? undefined
: yield* OtlpTracer.make({
url: otlpTracesUrl.value,
exportInterval: `${environment.otlpExportIntervalMs} millis`,
resource: {
serviceName: "desktop",
attributes: {
"service.runtime": "desktop",
"service.mode": environment.isDevelopment ? "development" : "packaged",
},
},
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
});
return Layer.succeed(Tracer.Tracer, tracer);
}),
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
backendOutputLogLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
Layer.succeed(References.TracerTimingEnabled, true),
);
+21
View File
@@ -0,0 +1,21 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
export interface DesktopStateShape {
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"t3/desktop/State",
) {}
export const layer = Layer.effect(
DesktopState,
Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
}),
);
@@ -0,0 +1,195 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
observability: Schema.Struct({
otlpTracesUrl: Schema.String,
otlpMetricsUrl: Schema.String,
}),
});
const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
);
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
port: 4888,
bindHost: "0.0.0.0",
httpBaseUrl: new URL("http://127.0.0.1:4888"),
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
}),
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposureShape);
function makeEnvironmentLayer(
baseDir: string,
options?: {
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
},
) {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: options?.isPackaged ?? true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: baseDir,
T3CODE_PORT: "9999",
T3CODE_MODE: "desktop",
T3CODE_DESKTOP_LAN_HOST: "192.168.1.50",
VITE_DEV_SERVER_URL: options?.devServerUrl,
}),
),
),
);
}
const withHarness = <A, E, R>(
effect: Effect.Effect<
A,
E,
| R
| DesktopEnvironment.DesktopEnvironment
| FileSystem.FileSystem
| DesktopBackendConfiguration.DesktopBackendConfiguration
>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
return yield* effect.pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
describe("DesktopBackendConfiguration", () => {
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const first = yield* configuration.resolve;
const second = yield* configuration.resolve;
assert.equal(first.executablePath, process.execPath);
assert.equal(first.entryPath, environment.backendEntryPath);
assert.equal(first.cwd, environment.backendCwd);
assert.equal(first.captureOutput, true);
assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
assert.isUndefined(first.env.T3CODE_PORT);
assert.isUndefined(first.env.T3CODE_MODE);
assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
assert.equal(first.bootstrap.mode, "desktop");
assert.equal(first.bootstrap.noBrowser, true);
assert.equal(first.bootstrap.port, 4888);
assert.equal(first.bootstrap.host, "0.0.0.0");
assert.equal(first.bootstrap.t3Home, environment.baseDir);
assert.equal(first.bootstrap.tailscaleServeEnabled, true);
assert.equal(first.bootstrap.tailscaleServePort, 8443);
assert.match(first.bootstrap.desktopBootstrapToken, /^[0-9a-f]{48}$/i);
assert.equal(second.bootstrap.desktopBootstrapToken, first.bootstrap.desktopBootstrapToken);
}),
),
);
it.effect("includes persisted backend observability endpoints when present", () =>
withHarness(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), {
recursive: true,
});
yield* fileSystem.writeFileString(
environment.serverSettingsPath,
yield* encodePersistedServerObservabilitySettingsDocument({
observability: {
otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ",
otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ",
},
}),
);
const config = yield* configuration.resolve;
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
}),
),
);
it.effect("omits backend observability endpoints when settings are missing", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
}),
),
);
it.effect("captures backend output in development so child process logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
assert.equal(config.captureOutput, true);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
isPackaged: false,
devServerUrl: "http://127.0.0.1:5733",
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,170 @@
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
DesktopBackendConfigurationShape
>()("t3/desktop/BackendConfiguration") {}
interface BackendObservabilitySettings {
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpMetricsUrl: Option.Option<string>;
}
const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
otlpTracesUrl: Option.none(),
otlpMetricsUrl: Option.none(),
};
const DESKTOP_BACKEND_ENV_NAMES = [
"T3CODE_PORT",
"T3CODE_MODE",
"T3CODE_NO_BROWSER",
"T3CODE_HOST",
"T3CODE_DESKTOP_WS_URL",
"T3CODE_DESKTOP_LAN_ACCESS",
"T3CODE_DESKTOP_LAN_HOST",
"T3CODE_DESKTOP_HTTPS_ENDPOINTS",
"T3CODE_TAILSCALE_SERVE",
"T3CODE_TAILSCALE_SERVE_PORT",
] as const;
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const exists = yield* fileSystem
.exists(environment.serverSettingsPath)
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return emptyBackendObservabilitySettings;
}
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings;
}
const parsed = parsePersistedServerObservabilitySettings(raw.value);
return {
otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
};
});
const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootstrapToken")(
function* (tokenRef: Ref.Ref<Option.Option<string>>) {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
let token = "";
while (token.length < 48) {
token += (yield* Random.nextUUIDv4).replace(/-/g, "");
}
token = token.slice(0, 48);
yield* Ref.set(tokenRef, Option.some(token));
return token;
},
);
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
> {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const backendExposure = yield* serverExposure.backendConfig;
return {
executablePath: process.execPath,
entryPath: environment.backendEntryPath,
cwd: environment.backendCwd,
env: {
...backendChildEnvPatch(),
ELECTRON_RUN_AS_NODE: "1",
},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: backendExposure.port,
t3Home: environment.baseDir,
host: backendExposure.bindHost,
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
...Option.match(input.observabilitySettings.otlpTracesUrl, {
onNone: () => ({}),
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
}),
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
onNone: () => ({}),
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
}),
},
httpBaseUrl: backendExposure.httpBaseUrl,
captureOutput: true,
};
},
);
export const layer = Layer.effect(
DesktopBackendConfiguration,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const tokenRef = yield* Ref.make(Option.none<string>());
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef);
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
});
}),
);
@@ -0,0 +1,494 @@
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: { ELECTRON_RUN_AS_NODE: "1" },
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
const configWithObservability: DesktopBackendBootstrapValue = {
...baseConfig.bootstrap,
tailscaleServeEnabled: true,
otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: options?.stdout ?? Stream.empty,
stderr: options?.stderr ?? Stream.empty,
all: Stream.merge(options?.stdout ?? Stream.empty, options?.stderr ?? Stream.empty),
exitCode: options?.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: options?.kill ?? (() => Effect.void),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
}
function responseForRequest(
request: HttpClientRequest.HttpClientRequest,
status: number,
): HttpClientResponse.HttpClientResponse {
return HttpClientResponse.fromWeb(request, new Response(null, { status }));
}
function httpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
const healthyHttpClientLayer = httpClientLayer((request) =>
Effect.succeed(responseForRequest(request, 200)),
);
function decodeBootstrap(raw: string) {
return decodeDesktopBackendBootstrap(raw);
}
function makeManagerLayer(input: {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) {
return DesktopBackendManager.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolve: Effect.succeed(input.config ?? baseConfig),
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
input.desktopState
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
: DesktopState.layer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
handleBackendReady: Effect.void,
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
...input.desktopWindow,
} satisfies DesktopWindow.DesktopWindowShape),
),
),
);
}
describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
spawnedCommand = command;
if (command._tag === "StandardCommand") {
const fd3 = command.options.additionalFds?.fd3;
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
}
return makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const managerLayer = makeManagerLayer({
config: {
...baseConfig,
bootstrap: configWithObservability,
},
spawnerLayer,
desktopWindow: {
handleBackendReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* Queue.take(exited);
assert.equal(readyCount, 1);
assert.isDefined(spawnedCommand);
if (spawnedCommand._tag !== "StandardCommand") {
throw new Error("Expected backend to spawn a standard command.");
}
assert.equal(spawnedCommand.command, "/electron");
assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
assert.equal(spawnedCommand.options.cwd, "/server");
assert.equal(spawnedCommand.options.extendEnv, true);
assert.equal(spawnedCommand.options.stdout, "pipe");
assert.equal(spawnedCommand.options.stderr, "pipe");
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
assert.isDefined(spawnedCommand.options.forceKillAfter);
assert.equal(
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
2_000,
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
}).pipe(Effect.provide(managerLayer));
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
const statuses = [503, 200];
let readyCount = 0;
const firstRequest = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer((request) =>
Effect.gen(function* () {
const status = statuses.shift();
assert.isDefined(status);
requestUrls.push(request.url);
yield* Deferred.succeed(firstRequest, void 0);
return responseForRequest(request, status);
}),
),
desktopWindow: {
handleBackendReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* Deferred.await(firstRequest);
assert.equal(readyCount, 0);
assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]);
yield* TestClock.adjust(Duration.millis(100));
yield* Queue.take(exited);
assert.equal(readyCount, 1);
assert.deepEqual(requestUrls, [
"http://127.0.0.1:3773/.well-known/t3/environment",
"http://127.0.0.1:3773/.well-known/t3/environment",
]);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("starts the configured backend and closes the scoped process on stop", () =>
Effect.gen(function* () {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReady = yield* Ref.make(false);
const quitting = yield* Ref.make(false);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
desktopState: {
backendReady,
quitting,
},
desktopWindow: {
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
assert.isTrue(Option.isNone(yield* manager.currentConfig));
yield* manager.start;
assert.equal(yield* Queue.take(startedPids), 123);
yield* Deferred.await(ready);
assert.isTrue(yield* Ref.get(backendReady));
assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
const runningSnapshot = yield* manager.snapshot;
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
yield* manager.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
const stoppedSnapshot = yield* manager.snapshot;
assert.isFalse(yield* Ref.get(backendReady));
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
}).pipe(Effect.provide(managerLayer));
}),
);
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
yield* TestClock.adjust(Duration.millis(499));
assert.equal(yield* Queue.size(starts), 0);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(yield* Queue.take(starts), 2);
yield* TestClock.adjust(Duration.millis(999));
assert.equal(yield* Queue.size(starts), 0);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(yield* Queue.take(starts), 3);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("cancels a scheduled restart when start is requested manually", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const secondClosed = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
return makeProcess({
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
});
}
const scope = yield* Scope.Scope;
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(secondClosed).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
kill: () => close,
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
yield* manager.start;
assert.equal(yield* Queue.take(starts), 2);
yield* manager.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("does not restart after stop cancels a scheduled restart", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* manager.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* manager.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
assert.equal((yield* manager.snapshot).desiredRunning, false);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
});
@@ -0,0 +1,596 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface DesktopBackendStartConfig {
readonly executablePath: string;
readonly entryPath: string;
readonly cwd: string;
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
readonly url: URL;
}> {
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
"BackendProcessBootstrapEncodeError",
)<{
readonly cause: Schema.SchemaError;
}> {
override get message() {
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
}
}
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
readonly cause: PlatformError.PlatformError;
}> {
override get message() {
return `Failed to spawn desktop backend process: ${this.cause.message}`;
}
}
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
readonly desiredRunning: boolean;
readonly ready: boolean;
readonly activePid: Option.Option<number>;
readonly restartAttempt: number;
readonly restartScheduled: boolean;
}
export interface DesktopBackendManagerShape {
readonly start: Effect.Effect<void>;
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
}
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
DesktopBackendManagerShape
>()("t3/desktop/BackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
interface ActiveBackendRun {
readonly id: number;
readonly scope: Scope.Closeable;
readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
readonly pid: Option.Option<number>;
}
interface BackendManagerState {
readonly desiredRunning: boolean;
readonly ready: boolean;
readonly config: Option.Option<DesktopBackendStartConfig>;
readonly active: Option.Option<ActiveBackendRun>;
readonly restartAttempt: number;
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
readonly nextRunId: number;
}
const initialState: BackendManagerState = {
desiredRunning: false,
ready: false,
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
Option.flatMap(active, (run) => run.pid);
const withActiveRun =
(runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
(state: BackendManagerState): BackendManagerState => ({
...state,
active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
});
const calculateRestartDelay = (attempt: number): Duration.Duration =>
Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
const closeRun = (
run: ActiveBackendRun,
options?: { readonly timeout?: Duration.Duration },
): Effect.Effect<void> => {
const waitForFiber = Option.match(run.fiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
});
const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
return (
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
).pipe(Effect.ignore);
};
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
);
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
);
});
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const command = ChildProcess.make(
options.executablePath,
[options.entryPath, "--bootstrap-fd", "3"],
{
cwd: options.cwd,
env: options.env,
extendEnv: true,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
stdin: "ignore",
stdout: options.captureOutput ? "pipe" : "inherit",
stderr: options.captureOutput ? "pipe" : "inherit",
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
additionalFds: {
fd3: {
type: "input",
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
},
},
},
);
const handle = yield* spawner
.spawn(command)
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const desktopState = yield* DesktopState.DesktopState;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
const mutex = yield* Semaphore.make(1);
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
Ref.update(state, withActiveRun(runId, f));
const snapshot = Ref.get(state).pipe(
Effect.map(
(current): DesktopBackendSnapshot => ({
desiredRunning: current.desiredRunning,
ready: current.ready,
activePid: activePid(current.active),
restartAttempt: current.restartAttempt,
restartScheduled: Option.isSome(current.restartFiber),
}),
),
);
const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
const cancelRestart = Effect.gen(function* () {
const restartFiber = yield* Ref.modify(state, (current) => [
current.restartFiber,
{
...current,
restartFiber: Option.none(),
},
]);
yield* Option.match(restartFiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
});
});
const start: Effect.Effect<void> = Effect.suspend(() =>
mutex.withPermits(1)(
Effect.gen(function* () {
const current = yield* Ref.get(state);
if (Option.isSome(current.active)) {
return;
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve;
const entryExists = yield* fileSystem
.exists(config.entryPath)
.pipe(Effect.orElseSucceed(() => false));
yield* cancelRestart;
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config),
}));
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
return;
}
const runScope = yield* Scope.make("sequential");
const runId = yield* Ref.modify(state, (latest) => [
latest.nextRunId,
{
...latest,
active: Option.some({
id: latest.nextRunId,
scope: runScope,
fiber: Option.none(),
pid: Option.none(),
} satisfies ActiveBackendRun),
nextRunId: latest.nextRunId + 1,
},
]);
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
Effect.gen(function* () {
const { isCurrentRun, nextState, pid } = yield* Ref.modify(
state,
(
latest,
): readonly [
{
readonly isCurrentRun: boolean;
readonly nextState: BackendManagerState;
readonly pid: Option.Option<number>;
},
BackendManagerState,
] => {
const currentRun = Option.getOrUndefined(latest.active);
if (currentRun?.id !== runId) {
return [
{
isCurrentRun: false,
nextState: latest,
pid: Option.none<number>(),
},
latest,
] as const;
}
const next = {
...latest,
active: Option.none<ActiveBackendRun>(),
ready: false,
};
return [
{
isCurrentRun: true,
nextState: next,
pid: currentRun.pid,
},
next,
] as const;
},
);
if (isCurrentRun) {
if (Option.isSome(pid)) {
yield* backendOutputLog.writeSessionBoundary({
phase: "END",
details: `pid=${pid.value} ${reason}`,
});
}
yield* Ref.set(desktopState.backendReady, false);
}
if (isCurrentRun && nextState.desiredRunning) {
yield* scheduleRestart(reason);
}
}),
);
});
const program = runBackendProcess({
...config,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
if (activeRun?.id !== runId) {
return [false, latest] as const;
}
return [
true,
{
...latest,
restartAttempt: 0,
ready: true,
},
] as const;
});
if (!isCurrentRun) {
return;
}
yield* Ref.set(desktopState.backendReady, true);
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
message: error.message,
}),
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
onFailure: (error) => finalizeRun(error.message),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
);
const fiber = yield* Effect.forkIn(program, parentScope);
yield* updateActiveRun(runId, (run) => ({
...run,
fiber: Option.some(fiber),
}));
}),
),
).pipe(Effect.withSpan("desktop.backendManager.start"));
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
reason: string,
) {
const scheduled = yield* Ref.modify(state, (latest) => {
if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
return [Option.none<Duration.Duration>(), latest] as const;
}
const delay = calculateRestartDelay(latest.restartAttempt);
return [
Option.some(delay),
{
...latest,
restartAttempt: latest.restartAttempt + 1,
},
] as const;
});
yield* Option.match(scheduled, {
onNone: () => Effect.void,
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
reason,
delayMs: Duration.toMillis(delay),
});
const restartFiber = yield* Effect.forkIn(
Effect.sleep(delay).pipe(
Effect.andThen(
Ref.modify(state, (latest) => {
const shouldRestart = latest.desiredRunning;
return [
shouldRestart,
{
...latest,
restartFiber: Option.none(),
},
] as const;
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) =>
logBackendManagerError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
),
parentScope,
);
yield* Ref.update(state, (latest) =>
Option.isNone(latest.restartFiber)
? {
...latest,
restartFiber: Option.some(restartFiber),
}
: latest,
);
}),
});
});
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
Effect.gen(function* () {
const result = yield* Ref.modify(state, (latest) => [
{
active: latest.active,
restartFiber: latest.restartFiber,
},
{
...latest,
desiredRunning: false,
ready: false,
active: Option.none<ActiveBackendRun>(),
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
yield* Ref.set(desktopState.backendReady, false);
return result;
}),
);
yield* Option.match(restartFiber, {
onNone: () => Effect.void,
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
});
yield* Option.match(active, {
onNone: () => Effect.void,
onSome: (run) => closeRun(run, options),
});
});
yield* Effect.addFinalizer(() => stop());
return DesktopBackendManager.of({
start,
stop,
currentConfig,
snapshot,
});
});
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
@@ -0,0 +1,365 @@
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopEnvironment,
layer as makeDesktopEnvironmentLayer,
} from "../app/DesktopEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const encoder = new TextEncoder();
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
en0: [
{
address: "192.168.1.20",
family: "IPv4",
internal: false,
},
],
};
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
tailscale0: [
{
address: "100.90.1.2",
family: "IPv4",
internal: false,
},
],
};
function mockSpawnerLayer(statusJson = "{}") {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(statusJson)),
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
),
),
);
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir, ...env })),
),
);
}
function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
});
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
);
}
const withHarness = <A, E, R>(
networkInterfaces: DesktopNetworkInterfaces,
effect: Effect.Effect<
A,
E,
| R
| DesktopEnvironment
| FileSystem.FileSystem
| DesktopServerExposure.DesktopServerExposure
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-server-exposure-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
it.effect("falls back to local-only without losing the requested network preference", () =>
withHarness(
emptyNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.setServerExposureMode("network-accessible");
const state = yield* serverExposure.configureFromSettings({ port: 4173 });
assert.equal(state.mode, "local-only");
assert.equal(state.endpointUrl, null);
assert.equal((yield* settings.get).serverExposureMode, "network-accessible");
const backendConfig = yield* serverExposure.backendConfig;
assert.equal(backendConfig.bindHost, "127.0.0.1");
assert.equal(backendConfig.httpBaseUrl.href, "http://127.0.0.1:4173/");
}),
),
);
it.effect("returns a typed error when network access is explicitly unavailable", () =>
withHarness(
emptyNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const error = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
assert.ok(error._tag === "DesktopServerExposureNoNetworkAddressError");
assert.equal(error.port, 4173);
}),
),
);
it.effect("persists network-accessible mode and updates backend binding state", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.load;
yield* serverExposure.configureFromSettings({ port: 4173 });
const change = yield* serverExposure.setMode("network-accessible");
assert.equal(change.requiresRelaunch, true);
assert.deepEqual(change.state, {
mode: "network-accessible",
endpointUrl: "http://192.168.1.20:4173",
advertisedHost: "192.168.1.20",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const backendConfig = yield* serverExposure.backendConfig;
assert.equal(backendConfig.bindHost, "0.0.0.0");
assert.equal(backendConfig.httpBaseUrl.href, "http://127.0.0.1:4173/");
const persisted = yield* settings.get;
assert.equal(persisted.serverExposureMode, "network-accessible");
}),
),
);
it.effect("persists tailscale serve preferences atomically and reports no-op updates", () =>
withHarness(
emptyNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.load;
yield* serverExposure.configureFromSettings({ port: 4173 });
const changed = yield* serverExposure.setTailscaleServeEnabled({
enabled: true,
port: 8443,
});
assert.equal(changed.requiresRelaunch, true);
assert.equal(changed.state.tailscaleServeEnabled, true);
assert.equal(changed.state.tailscaleServePort, 8443);
const unchanged = yield* serverExposure.setTailscaleServeEnabled({
enabled: true,
port: 8443,
});
assert.equal(unchanged.requiresRelaunch, false);
const persisted = yield* settings.get;
assert.equal(persisted.tailscaleServeEnabled, true);
assert.equal(persisted.tailscaleServePort, 8443);
}),
),
);
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
withHarness(
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
yield* serverExposure.setMode("network-accessible");
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/", "http://192.168.1.20:4173/", "http://100.90.1.2:4173/"],
);
}),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const change = yield* serverExposure.setMode("network-accessible");
assert.equal(change.state.advertisedHost, "10.0.0.7");
assert.equal(change.state.endpointUrl, "http://10.0.0.7:4173");
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/", "http://10.0.0.7:4173/", "https://public.example.test/"],
);
}),
{
T3CODE_DESKTOP_LAN_HOST: "10.0.0.7",
T3CODE_DESKTOP_HTTPS_ENDPOINTS: "https://public.example.test",
},
),
);
it.effect("advertises loopback, LAN, and configured manual endpoints from runtime state", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 3773 });
yield* serverExposure.setMode("network-accessible");
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
assert.deepEqual(endpoints, [
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
description: "Loopback endpoint for this desktop app.",
},
{
id: "desktop-lan:http://192.168.1.20:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://192.168.1.20:3773/",
wsBaseUrl: "ws://192.168.1.20:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
},
{
id: "manual:https://desktop.example.ts.net",
label: "Custom HTTPS",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "https://desktop.example.ts.net/",
wsBaseUrl: "wss://desktop.example.ts.net/",
reachability: "public",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
},
{
id: "manual:http://desktop.example.test:3773",
label: "Custom endpoint",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://desktop.example.test:3773/",
wsBaseUrl: "ws://desktop.example.test:3773/",
reachability: "public",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured endpoint for this desktop backend.",
},
]);
}),
{
T3CODE_DESKTOP_HTTPS_ENDPOINTS:
"https://desktop.example.ts.net,http://desktop.example.test:3773,not-a-url",
},
),
);
});
@@ -0,0 +1,548 @@
import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
DesktopServerExposureState,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type DesktopNetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
interface ResolvedDesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
readonly localHttpUrl: string;
readonly localWsUrl: string;
readonly endpointUrl: string | null;
readonly advertisedHost: string | null;
}
interface DesktopAdvertisedEndpointInput {
readonly port: number;
readonly exposure: ResolvedDesktopServerExposure;
readonly customHttpsEndpointUrls?: readonly string[];
}
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
};
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
};
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.");
const isHttpsEndpointUrl = (value: string): boolean => {
try {
return new URL(value).protocol === "https:";
} catch {
return false;
}
};
const resolveLanAdvertisedHost = (
networkInterfaces: DesktopNetworkInterfaces,
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;
};
const resolveDesktopServerExposure = (input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride?: string;
}): ResolvedDesktopServerExposure => {
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,
};
};
const createDesktopEndpoint = (
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint =>
createAdvertisedEndpoint({
...input,
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
source: "desktop-core",
});
const createManualEndpoint = (
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint =>
createAdvertisedEndpoint({
...input,
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
source: "user",
});
const resolveDesktopCoreAdvertisedEndpoints = (
input: DesktopAdvertisedEndpointInput,
): readonly AdvertisedEndpoint[] => {
const endpoints: AdvertisedEndpoint[] = [
createDesktopEndpoint({
id: `desktop-loopback:${input.port}`,
label: "This machine",
httpBaseUrl: input.exposure.localHttpUrl,
reachability: "loopback",
status: "available",
description: "Loopback endpoint for this desktop app.",
}),
];
if (input.exposure.endpointUrl) {
endpoints.push(
createDesktopEndpoint({
id: `desktop-lan:${input.exposure.endpointUrl}`,
label: "Local network",
httpBaseUrl: input.exposure.endpointUrl,
reachability: "lan",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
}),
);
}
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
try {
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
endpoints.push(
createManualEndpoint({
id: `manual:${customEndpointUrl}`,
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
httpBaseUrl: customEndpointUrl,
reachability: "public",
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
status: "unknown",
description: isHttpsEndpoint
? "User-configured HTTPS endpoint for this desktop backend."
: "User-configured endpoint for this desktop backend.",
}),
);
} catch {
// Ignore malformed user-configured endpoints without dropping valid endpoints.
}
}
return endpoints;
};
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
"DesktopServerExposureNoNetworkAddressError",
)<{
readonly port: number;
}> {
override get message() {
return `No reachable network address is available for desktop network access on port ${this.port}.`;
}
}
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
"DesktopServerExposurePersistenceError",
)<{
readonly operation: DesktopServerExposurePersistenceOperation;
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
}> {
override get message() {
return `Failed to persist desktop ${this.operation} settings.`;
}
}
export type DesktopServerExposureSetModeError =
| DesktopServerExposureNoNetworkAddressError
| DesktopServerExposurePersistenceError;
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
export interface DesktopServerExposureBackendConfig {
readonly port: number;
readonly bindHost: string;
readonly httpBaseUrl: URL;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
}
export interface DesktopServerExposureChange {
readonly state: DesktopServerExposureState;
readonly requiresRelaunch: boolean;
}
export interface DesktopServerExposureShape {
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
DesktopServerExposureShape
>()("t3/desktop/ServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
}
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("t3/desktop/ServerExposure/NetworkInterfaces") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly bindHost: string;
readonly localHttpUrl: string;
readonly localWsUrl: string;
readonly httpBaseUrl: URL;
readonly endpointUrl: Option.Option<string>;
readonly advertisedHost: Option.Option<string>;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
}
interface ResolvedRuntimeState {
readonly state: RuntimeState;
readonly unavailable: boolean;
}
const initialRuntimeState = (): RuntimeState =>
runtimeStateFromResolvedExposure({
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DEFAULT_DESKTOP_SETTINGS,
exposure: resolveDesktopServerExposure({
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
port: 0,
networkInterfaces: {},
}),
port: 0,
});
const toContractState = (state: RuntimeState): DesktopServerExposureState => ({
mode: state.mode,
endpointUrl: Option.getOrNull(state.endpointUrl),
advertisedHost: Option.getOrNull(state.advertisedHost),
tailscaleServeEnabled: state.tailscaleServeEnabled,
tailscaleServePort: state.tailscaleServePort,
});
const toBackendConfig = (state: RuntimeState): DesktopServerExposureBackendConfig => ({
port: state.port,
bindHost: state.bindHost,
httpBaseUrl: state.httpBaseUrl,
tailscaleServeEnabled: state.tailscaleServeEnabled,
tailscaleServePort: state.tailscaleServePort,
});
const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure => ({
mode: state.mode,
bindHost: state.bindHost,
localHttpUrl: state.localHttpUrl,
localWsUrl: state.localWsUrl,
endpointUrl: Option.getOrNull(state.endpointUrl),
advertisedHost: Option.getOrNull(state.advertisedHost),
});
function runtimeStateFromResolvedExposure(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopSettings;
readonly exposure: ResolvedDesktopServerExposure;
readonly port: number;
}): RuntimeState {
return {
requestedMode: input.requestedMode,
mode: input.exposure.mode,
port: input.port,
bindHost: input.exposure.bindHost,
localHttpUrl: input.exposure.localHttpUrl,
localWsUrl: input.exposure.localWsUrl,
httpBaseUrl: new URL(input.exposure.localHttpUrl),
endpointUrl: Option.fromNullishOr(input.exposure.endpointUrl),
advertisedHost: Option.fromNullishOr(input.exposure.advertisedHost),
tailscaleServeEnabled: input.settings.tailscaleServeEnabled,
tailscaleServePort: input.settings.tailscaleServePort,
};
}
function resolveRuntimeState(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopSettings;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly advertisedHostOverride: Option.Option<string>;
}): ResolvedRuntimeState {
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
const requestedExposure = resolveDesktopServerExposure({
mode: input.requestedMode,
port: input.port,
networkInterfaces: input.networkInterfaces,
...(advertisedHostOverride ? { advertisedHostOverride } : {}),
});
const unavailable =
input.requestedMode === "network-accessible" && requestedExposure.endpointUrl === null;
const exposure = unavailable
? resolveDesktopServerExposure({
mode: "local-only",
port: input.port,
networkInterfaces: input.networkInterfaces,
...(advertisedHostOverride ? { advertisedHostOverride } : {}),
})
: requestedExposure;
return {
state: runtimeStateFromResolvedExposure({
requestedMode: input.requestedMode,
settings: input.settings,
exposure,
port: input.port,
}),
unavailable,
};
}
const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): boolean =>
previous.port !== next.port ||
previous.bindHost !== next.bindHost ||
previous.localHttpUrl !== next.localHttpUrl;
const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const networkInterfaces = yield* DesktopNetworkInterfacesService;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
const readNetworkInterfaces = networkInterfaces.read;
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
const backendConfig = Ref.get(stateRef).pipe(Effect.map(toBackendConfig));
const configureFromSettings = Effect.fn("desktop.serverExposure.configureFromSettings")(
function* ({ port }: { readonly port: number }) {
yield* Effect.annotateCurrentSpan({ port });
const settings = yield* desktopSettings.get;
const currentNetworkInterfaces = yield* readNetworkInterfaces;
const resolved = resolveRuntimeState({
requestedMode: settings.serverExposureMode,
settings,
port,
networkInterfaces: currentNetworkInterfaces,
advertisedHostOverride: config.desktopLanHostOverride,
});
yield* Ref.set(stateRef, resolved.state);
return toContractState(resolved.state);
},
);
const setMode = Effect.fn("desktop.serverExposure.setMode")(function* (
mode: DesktopServerExposureMode,
) {
yield* Effect.annotateCurrentSpan({ mode });
const previous = yield* Ref.get(stateRef);
const currentSettings = yield* desktopSettings.get;
const nextSettings = {
...currentSettings,
serverExposureMode: mode,
};
const currentNetworkInterfaces = yield* readNetworkInterfaces;
const resolved = resolveRuntimeState({
requestedMode: mode,
settings: nextSettings,
port: previous.port,
networkInterfaces: currentNetworkInterfaces,
advertisedHostOverride: config.desktopLanHostOverride,
});
if (resolved.unavailable) {
return yield* new DesktopServerExposureNoNetworkAddressError({ port: previous.port });
}
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "server-exposure-mode",
cause,
}),
),
);
yield* Ref.set(stateRef, resolved.state);
return {
state: toContractState(resolved.state),
requiresRelaunch: change.changed || requiresBackendRelaunch(previous, resolved.state),
};
});
const setTailscaleServeEnabled = Effect.fn("desktop.serverExposure.setTailscaleServeEnabled")(
function* (input: { readonly enabled: boolean; readonly port?: number }) {
yield* Effect.annotateCurrentSpan({
enabled: input.enabled,
...(input.port === undefined ? {} : { port: input.port }),
});
const result = yield* desktopSettings
.setTailscaleServe({
enabled: input.enabled,
port: Option.fromNullishOr(input.port),
})
.pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "tailscale-serve",
cause,
}),
),
);
const nextState = yield* Ref.updateAndGet(stateRef, (current) => ({
...current,
tailscaleServeEnabled: result.settings.tailscaleServeEnabled,
tailscaleServePort: result.settings.tailscaleServePort,
}));
return {
state: toContractState(nextState),
requiresRelaunch: result.changed,
};
},
);
const getAdvertisedEndpoints = Effect.gen(function* () {
const state = yield* Ref.get(stateRef);
const currentNetworkInterfaces = yield* readNetworkInterfaces;
const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
port: state.port,
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
return [...coreEndpoints, ...tailscaleEndpoints];
}).pipe(Effect.withSpan("desktop.serverExposure.getAdvertisedEndpoints"));
return DesktopServerExposure.of({
getState,
backendConfig,
configureFromSettings,
setMode,
setTailscaleServeEnabled,
getAdvertisedEndpoints,
});
});
export const layer = Layer.effect(DesktopServerExposure, make);
export const networkInterfacesLayer = Layer.succeed(
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesService.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
}),
);
@@ -0,0 +1,142 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
resolveTailscaleAdvertisedEndpoints,
} from "./tailscaleEndpointProvider.ts";
const unusedTailscaleExternalServicesLayer = Layer.mergeAll(
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected Tailscale HTTPS probe")),
),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale status process")),
),
);
describe("tailscale endpoint provider", () => {
it("detects Tailnet IPv4 addresses", () => {
assert.equal(isTailscaleIpv4Address("100.64.0.1"), true);
assert.equal(isTailscaleIpv4Address("100.127.255.254"), true);
assert.equal(isTailscaleIpv4Address("100.128.0.1"), false);
assert.equal(isTailscaleIpv4Address("192.168.1.44"), false);
});
it.effect("parses MagicDNS names from tailscale status", () =>
Effect.gen(function* () {
const dnsName = yield* parseTailscaleMagicDnsName(
`{"Self":{"DNSName":"desktop.tail.ts.net."}}`,
);
assert.equal(dnsName, "desktop.tail.ts.net");
assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
const malformed = yield* Effect.result(parseTailscaleMagicDnsName("not-json"));
assert.isTrue(malformed._tag === "Failure");
}),
);
it.effect("resolves Tailscale endpoints as add-on advertised endpoints", () =>
Effect.gen(function* () {
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {
tailscale0: [
{
address: "100.100.100.100",
family: "IPv4",
internal: false,
netmask: "255.192.0.0",
cidr: "100.100.100.100/10",
mac: "00:00:00:00:00:00",
},
],
},
statusJson: `{"Self":{"DNSName":"desktop.tail.ts.net."}}`,
});
assert.deepEqual(endpoints, [
{
id: "tailscale-ip:http://100.100.100.100:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.100.100.100:3773/",
wsBaseUrl: "ws://100.100.100.100:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "Reachable from devices on the same Tailnet.",
},
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "requires-configuration",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "unavailable",
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
},
]);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
Effect.gen(function* () {
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
statusJson: `{"Self":{"DNSName":"desktop.tail.ts.net."}}`,
serveEnabled: true,
probe: () => Effect.succeed(true),
});
assert.deepEqual(endpoints, [
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "HTTPS endpoint served by Tailscale Serve.",
},
]);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
});
@@ -0,0 +1,138 @@
import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
probeTailscaleHttpsEndpoint,
readTailscaleStatus,
} from "@t3tools/tailscale";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
};
function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isTailscaleIpv4Address(address.address)) continue;
if (seen.has(address.address)) continue;
seen.add(address.address);
endpoints.push(
createAdvertisedEndpoint({
provider: TAILSCALE_ENDPOINT_PROVIDER,
source: "desktop-addon",
id: `tailscale-ip:http://${address.address}:${input.port}`,
label: "Tailscale IP",
httpBaseUrl: `http://${address.address}:${input.port}`,
reachability: "private-network",
status: "available",
description: "Reachable from devices on the same Tailnet.",
}),
);
}
}
return endpoints;
}
const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn(
"resolveTailscaleMagicDnsAdvertisedEndpoint",
)(function* (input: {
readonly dnsName: string | null;
readonly serveEnabled: boolean;
readonly servePort?: number;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<Option.Option<AdvertisedEndpoint>, never, HttpClient.HttpClient> {
if (!input.dnsName) {
return Option.none();
}
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: input.dnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
});
const probe =
input.probe?.(httpBaseUrl) ??
probeTailscaleHttpsEndpoint({
baseUrl: httpBaseUrl,
});
const isReachable = input.serveEnabled ? yield* probe : false;
return Option.some(
createAdvertisedEndpoint({
provider: TAILSCALE_ENDPOINT_PROVIDER,
source: "desktop-addon",
id: `tailscale-magicdns:${httpBaseUrl}`,
label: "Tailscale HTTPS",
httpBaseUrl,
reachability: "private-network",
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
status: isReachable ? "available" : "unavailable",
description: isReachable
? "HTTPS endpoint served by Tailscale Serve."
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
}),
);
});
export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAdvertisedEndpoints")(
function* (input: {
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<
readonly AdvertisedEndpoint[],
never,
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
)
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
)
: null;
const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({
dnsName,
serveEnabled: input.serveEnabled === true,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
...(input.probe === undefined ? {} : { probe: input.probe }),
});
return Option.match(magicDnsEndpoint, {
onNone: () => ipEndpoints,
onSome: (endpoint) => [...ipEndpoints, endpoint],
});
},
);
-57
View File
@@ -1,57 +0,0 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
-26
View File
@@ -1,26 +0,0 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
@@ -0,0 +1,109 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
const {
appendSwitchMock,
exitMock,
getAppPathMock,
getVersionMock,
onMock,
quitMock,
relaunchMock,
removeListenerMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setDesktopNameMock,
setDockIconMock,
setNameMock,
setPathMock,
whenReadyMock,
} = vi.hoisted(() => ({
appendSwitchMock: vi.fn(),
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getVersionMock: vi.fn(() => "1.2.3"),
onMock: vi.fn(),
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setDesktopNameMock: vi.fn(),
setDockIconMock: vi.fn(),
setNameMock: vi.fn(),
setPathMock: vi.fn(),
whenReadyMock: vi.fn(() => Promise.resolve()),
}));
vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
},
dock: {
setIcon: setDockIconMock,
},
getAppPath: getAppPathMock,
getVersion: getVersionMock,
isPackaged: true,
name: "T3 Code",
on: onMock,
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAppUserModelId: setAppUserModelIdMock,
setDesktopName: setDesktopNameMock,
setName: setNameMock,
setPath: setPathMock,
whenReady: whenReadyMock,
exit: exitMock,
},
}));
import * as ElectronApp from "./ElectronApp.ts";
describe("ElectronApp", () => {
beforeEach(() => {
appendSwitchMock.mockClear();
exitMock.mockClear();
onMock.mockClear();
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
setPathMock.mockClear();
});
it.effect("reads app metadata through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const metadata = yield* electronApp.metadata;
assert.deepEqual(metadata, {
appVersion: "1.2.3",
appPath: "/app",
isPackaged: true,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: false,
});
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes app event listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
yield* Effect.scoped(
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.on("activate", listener);
}),
);
assert.deepEqual(onMock.mock.calls, [["activate", listener]]);
assert.deepEqual(removeListenerMock.mock.calls, [["activate", listener]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+118
View File
@@ -0,0 +1,118 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export interface ElectronAppMetadata {
readonly appVersion: string;
readonly appPath: string;
readonly isPackaged: boolean;
readonly resourcesPath: string;
readonly runningUnderArm64Translation: boolean;
}
export interface ElectronAppShape {
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"t3/desktop/electron/App",
) {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
): Effect.Effect<void, never, Scope.Scope> =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.app.on(eventName as any, listener as any);
}),
() =>
Effect.sync(() => {
Electron.app.removeListener(eventName as any, listener as any);
}),
).pipe(Effect.asVoid);
const make = ElectronApp.of({
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
})),
name: Effect.sync(() => Electron.app.name),
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
quit: Effect.sync(() => {
Electron.app.quit();
}),
exit: (code) =>
Effect.sync(() => {
Electron.app.exit(code);
}),
relaunch: (options) =>
Effect.sync(() => {
Electron.app.relaunch(options);
}),
setPath: (name, path) =>
Effect.sync(() => {
Electron.app.setPath(name, path);
}),
setName: (name) =>
Effect.sync(() => {
Electron.app.setName(name);
}),
setAboutPanelOptions: (options) =>
Effect.sync(() => {
Electron.app.setAboutPanelOptions(options);
}),
setAppUserModelId: (id) =>
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
setDesktopName: (desktopName) =>
Effect.sync(() => {
const linuxApp = Electron.app as Electron.App & {
setDesktopName?: (desktopName: string) => void;
};
linuxApp.setDesktopName?.(desktopName);
}),
setDockIcon: (iconPath) =>
Effect.sync(() => {
Electron.app.dock?.setIcon(iconPath);
}),
appendCommandLineSwitch: (switchName, value) =>
Effect.sync(() => {
if (value === undefined) {
Electron.app.commandLine.appendSwitch(switchName);
return;
}
Electron.app.commandLine.appendSwitch(switchName, value);
}),
on: addScopedAppListener,
});
export const layer = Layer.succeed(ElectronApp, make);
@@ -0,0 +1,93 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
import { beforeEach, vi } from "vitest";
import * as ElectronDialog from "./ElectronDialog.ts";
const { showMessageBoxMock, showOpenDialogMock, showErrorBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
showOpenDialogMock: vi.fn(),
showErrorBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
showOpenDialog: showOpenDialogMock,
showErrorBox: showErrorBoxMock,
},
}));
describe("ElectronDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
showOpenDialogMock.mockReset();
showErrorBoxMock.mockReset();
});
it.effect("returns false without opening a confirm dialog for empty messages", () =>
Effect.gen(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: " ",
owner: Option.none(),
});
assert.isFalse(result);
assert.equal(showMessageBoxMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens a confirm dialog for the owner window", () =>
Effect.gen(function* () {
const owner = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.some(owner),
});
assert.isTrue(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
owner,
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
Effect.gen(function* () {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.none(),
});
assert.isFalse(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
});
@@ -0,0 +1,84 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export interface ElectronDialogPickFolderInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
}
export interface ElectronDialogConfirmInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly message: string;
}
export interface ElectronDialogShape {
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"t3/desktop/electron/Dialog",
) {}
const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
properties: ["openDirectory", "createDirectory"],
}),
onSome: (defaultPath) => ({
properties: ["openDirectory", "createDirectory"],
defaultPath,
}),
});
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
onSome: (owner) =>
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
});
if (result.canceled) {
return Option.none();
}
return Option.fromNullishOr(result.filePaths[0]);
}),
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
showErrorBox: (title, content) =>
Effect.sync(() => {
Electron.dialog.showErrorBox(title, content);
}),
});
export const layer = Layer.succeed(ElectronDialog, make);
@@ -0,0 +1,119 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted(
() => ({
buildFromTemplateMock: vi.fn(),
createFromNamedImageMock: vi.fn(),
setApplicationMenuMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
Menu: {
buildFromTemplate: buildFromTemplateMock,
setApplicationMenu: setApplicationMenuMock,
},
nativeImage: {
createFromNamedImage: createFromNamedImageMock,
},
}));
import * as ElectronMenu from "./ElectronMenu.ts";
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
createFromNamedImageMock.mockReset();
setApplicationMenuMock.mockReset();
});
it.effect("returns none without building a menu when there are no valid items", () =>
Effect.gen(function* () {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
items: [],
position: Option.none(),
});
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with the clicked leaf item id", () =>
Effect.gen(function* () {
buildFromTemplateMock.mockImplementation(
(template: Electron.MenuItemConstructorOptions[]) => ({
popup: () => {
const firstItem = template[0];
assert.isDefined(firstItem);
const click = firstItem.click;
if (!click) {
throw new Error("Expected menu item to have a click handler.");
}
click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
},
}),
);
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
});
assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with none when the menu closes without a click", () =>
Effect.gen(function* () {
buildFromTemplateMock.mockImplementation(() => ({
popup: (options: Electron.PopupOptions) => {
options.callback?.();
},
}));
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.some({ x: 10.8, y: 20.2 }),
});
assert.isTrue(Option.isNone(selectedItemId));
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
label: "Copy",
enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
Effect.gen(function* () {
const popupMock = vi.fn();
buildFromTemplateMock.mockImplementation(() => ({ popup: popupMock }));
const electronMenu = yield* ElectronMenu.ElectronMenu;
const popup = electronMenu.popupTemplate({
window: {} as Electron.BrowserWindow,
template: [{ label: "Copy" }],
});
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
assert.equal(popupMock.mock.calls.length, 0);
yield* popup;
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1);
}).pipe(Effect.provide(ElectronMenu.layer)),
);
});
Loaded 100 of 1209 files, more files were not shown because too many files have changed in this diff. Show more