Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge de26297249 Add React Scan composer rerender recordings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-31 16:23:15 +00:00
Cursor AgentandJulius Marminge 0288ac4599 Stabilize composer error handler prop
Co-authored-by: Julius Marminge <[email protected]>
2026-05-31 16:21:49 +00:00
Cursor AgentandJulius Marminge f928ba2c65 Stabilize chat composer callback props
Co-authored-by: Julius Marminge <[email protected]>
2026-05-31 16:18:07 +00:00
Cursor AgentandJulius Marminge 8d271c0e85 Stabilize empty thread metadata for composer
Co-authored-by: Julius Marminge <[email protected]>
2026-05-31 16:15:28 +00:00
Cursor AgentandJulius Marminge d6585f6314 Reduce chat composer rerenders during streaming
Co-authored-by: Julius Marminge <[email protected]>
2026-05-31 16:13:39 +00:00
b3e8c0334b T3 Code Mobile [WIP] (#2013)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
2026-05-29 17:00:54 -07:00
Julius Marminge e3accd6e95 Ensure Electron runtime is installed in release workflow (#2861) 2026-05-29 09:38:25 -07:00
cf07d06321 Extract independent web cleanup from mobile stack (#2855)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-28 16:50:40 -07:00
Julius Marmingeandcodex 31268945f8 Extract collection performance refactors from mobile stack (#2854)
Co-authored-by: codex <[email protected]>
2026-05-28 16:18:58 -07:00
Julius Marminge 6b3050ee74 Migrate TypeScript checks to Effect TSGo (#2851) 2026-05-28 15:59:42 -07:00
Ibrahim Elkamali 83f0cc9e31 Add Claude Opus 4.8 support (#2849) 2026-05-28 18:43:48 +00:00
Julius Marmingeandcodex e6330ead82 [codex] Bump Effect to beta.73 and migrate compatibility APIs (#2840)
Co-authored-by: codex <[email protected]>
2026-05-28 11:13:50 -07: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
1415 changed files with 313381 additions and 49797 deletions

No files matched your search

+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"]
}
}
}
+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.
+2
View File
@@ -0,0 +1,2 @@
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
* text=auto eol=lf
+5 -1
View File
@@ -28,4 +28,8 @@ github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+46 -6
View File
@@ -9,7 +9,8 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -45,6 +46,14 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- name: Format
run: bun run fmt:check
@@ -70,12 +79,13 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
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: ubuntu-24.04
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -90,5 +100,35 @@ jobs:
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: node scripts/mobile-native-static-check.ts
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
+71 -31
View File
@@ -124,25 +124,52 @@ jobs:
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 testFilePatterns = [
/(^|\/)__tests__(\/|$)/,
/(^|\/)tests?(\/|$)/,
/^apps\/server\/integration\//,
/\.(test|spec|browser|integration)\.[^.\/]+$/,
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 isTestFile = (filename) =>
testFilePatterns.some((pattern) => pattern.test(filename));
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) {
@@ -168,40 +195,53 @@ jobs:
return "size:XXL";
};
const files = await github.paginate(
github.rest.pulls.listFiles,
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
stdio: "inherit",
});
execFileSync(
"git",
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber,
per_page: 100,
stdio: "inherit",
},
(response) => response.data,
);
if (files.length >= 3000) {
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
encoding: "utf8",
}).trim();
if (resolvedHeadSha !== headSha) {
core.warning(
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
);
}
let testChangedLines = 0;
let nonTestChangedLines = 0;
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
stdio: "inherit",
});
for (const file of files) {
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
const diffArgs = [
"diff",
"--numstat",
"--ignore-all-space",
"--ignore-blank-lines",
`${baseSha}...${resolvedHeadSha}`,
];
if (changedLinesForFile === 0) {
continue;
}
if (isTestFile(file.filename)) {
testChangedLines += changedLinesForFile;
continue;
}
nonTestChangedLines += changedLinesForFile;
}
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);
+488 -52
View File
@@ -1,59 +1,89 @@
name: Release Desktop
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: true
required: false
type: string
permissions:
contents: write
id-token: write
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
runs-on: ubuntu-24.04
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
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
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 "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$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
with:
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -68,6 +98,68 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- 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
@@ -77,34 +169,49 @@ jobs:
- 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: macos-14
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
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
@@ -128,6 +235,85 @@ jobs:
- 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:
@@ -204,18 +390,31 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
"release/*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
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:
@@ -226,7 +425,12 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
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
@@ -245,32 +449,53 @@ jobs:
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
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 run build --filter=@t3tools/web --filter=t3
run: bun --filter=t3 run build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
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]
runs-on: ubuntu-24.04
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:
@@ -280,17 +505,72 @@ jobs:
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
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: T3 Code v${{ needs.preflight.outputs.version }}
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 }}
@@ -300,13 +580,108 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
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: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
@@ -344,6 +719,9 @@ jobs:
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:
@@ -352,7 +730,7 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx oxfmt@0.40.0 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'
@@ -375,3 +753,61 @@ jobs:
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 }}"
+6
View File
@@ -12,6 +12,7 @@ packages/*/dist
build/
.logs/
release/
release-mock/
.t3
.idea/
apps/web/.playwright
@@ -20,3 +21,8 @@ apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+16 -2
View File
@@ -1,6 +1,7 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
@@ -8,7 +9,20 @@
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"apps/mobile/uniwind-types.d.ts",
"*.icon/**"
],
"sortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+9 -2
View File
@@ -6,17 +6,24 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"unicorn/no-array-sort": "off",
"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"
}
}
+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.
+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"
}
+1
View File
@@ -3,6 +3,7 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- If changing native mobile code, `bun lint:mobile` must also pass.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+2
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,6 +51,7 @@ 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 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
+40 -5
View File
@@ -1,19 +1,44 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
## How to use
## Installation
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
> T3 Code currently supports Codex, 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`
### Run without installing
```bash
npx t3
```
You can also just install the desktop app. It's cooler.
### Desktop app
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
## Some notes
@@ -21,8 +46,18 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Before local development, prepare the environment and install dependencies:
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
bun install .
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+175 -44
View File
@@ -1,68 +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. |
| `--base-dir <path>` | `T3CODE_HOME` | Base 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. Use this for standard CLI and remote-server flows. |
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
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.
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
- 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.
-2
View File
@@ -1,2 +0,0 @@
dist-electron/
.electron-runtime/
+14 -11
View File
@@ -1,31 +1,34 @@
{
"name": "@t3tools/desktop",
"version": "0.0.14",
"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",
"typecheck": "tsc --noEmit",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsgo --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "40.6.0",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2"
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+24 -15
View File
@@ -1,27 +1,39 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
if (!devServerUrl) {
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
}
const devServer = new URL(devServerUrl);
const port = Number.parseInt(devServer.port, 10);
if (!Number.isInteger(port) || port <= 0) {
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
}
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/index.mjs",
"dist-electron/main.cjs",
"dist-electron/preload.cjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
{ directory: "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 waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpHost: devServer.hostname,
tcpPort: port,
});
const childEnv = { ...process.env };
@@ -57,13 +69,10 @@ function startApp() {
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
{
cwd: desktopDir,
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
env: childEnv,
stdio: "inherit",
},
);
+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);
}
}
+241
View File
@@ -0,0 +1,241 @@
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
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 = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
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
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
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>()(
"@t3tools/desktop/app/DesktopAssets",
) {}
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,115 @@
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> = {},
) =>
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
>()("@t3tools/desktop/app/DesktopEnvironment") {}
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));
+236
View File
@@ -0,0 +1,236 @@
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>()(
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
) {}
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>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"@t3tools/desktop/app/DesktopLifecycle",
) {}
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
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
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>()(
"@t3tools/desktop/app/DesktopState",
) {}
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,169 @@
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
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 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,
PlatformError.PlatformError
>;
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
DesktopBackendConfigurationShape
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
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 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 crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
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,606 @@
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
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
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.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
);
if (Option.isNone(config)) {
return;
}
const entryExists = yield* fileSystem
.exists(config.value.entryPath)
.pipe(Effect.orElseSucceed(() => false));
yield* cancelRestart;
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
}));
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.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.value,
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.value.bootstrap.port} cwd=${config.value.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
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
}
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
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>()(
"@t3tools/desktop/electron/ElectronApp",
) {}
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>()(
"@t3tools/desktop/electron/ElectronDialog",
) {}
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)),
);
});
+181
View File
@@ -0,0 +1,181 @@
import type { ContextMenuItem } from "@t3tools/contracts";
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";
export interface ElectronMenuPosition {
readonly x: number;
readonly y: number;
}
export interface ElectronMenuContextInput {
readonly window: Electron.BrowserWindow;
readonly items: readonly ContextMenuItem[];
readonly position: Option.Option<ElectronMenuPosition>;
}
export interface ElectronMenuTemplateInput {
readonly window: Electron.BrowserWindow;
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
export interface ElectronMenuShape {
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
) {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
const normalizePosition = (
position: Option.Option<ElectronMenuPosition>,
): Option.Option<ElectronMenuPosition> =>
Option.filter(
position,
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
export const layer = Layer.sync(ElectronMenu, () => {
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (process.platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache;
}
try {
const icon = Electron.nativeImage.createFromNamedImage("trash").resize({
width: 12,
height: 12,
});
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
}
return destructiveMenuIconCache;
};
const buildTemplate = (
entries: readonly ContextMenuItem[],
complete: (selectedItemId: Option.Option<string>) => void,
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: Electron.MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children, complete);
} else {
itemOption.click = () => complete(Option.some(item.id));
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (Option.isSome(destructiveIcon)) {
itemOption.icon = destructiveIcon.value;
}
}
template.push(itemOption);
}
return template;
};
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
if (normalizedItems.length === 0) {
resume(Effect.succeed(Option.none()));
return;
}
let completed = false;
const complete = (selectedItemId: Option.Option<string>) => {
if (completed) {
return;
}
completed = true;
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
});
@@ -0,0 +1,105 @@
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 type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
vi.mock("electron", () => ({
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
});
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
),
),
);
it.effect("scopes registered file protocols", () =>
Effect.gen(function* () {
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
});
}),
);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
});
@@ -0,0 +1,272 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
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 Scope from "effect/Scope";
import * as Electron from "electron";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export const DESKTOP_SCHEME = "t3";
export class ElectronProtocolRegistrationError extends Data.TaggedError(
"ElectronProtocolRegistrationError",
)<{
readonly scheme: string;
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
}
}
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
}
export interface ElectronProtocolShape {
readonly registerFileProtocol: <E, R>(input: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
const make = Effect.gen(function* () {
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
const registered = Electron.protocol.registerFileProtocol(
scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
);
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
},
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
() =>
Effect.sync(() => {
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
}),
),
),
);
},
);
const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
});
export const layer = Layer.effect(ElectronProtocol, make);
@@ -0,0 +1,70 @@
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 Electron from "electron";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to check encryption availability.";
}
}
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
"ElectronSafeStorageEncryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to encrypt a string.";
}
}
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
"ElectronSafeStorageDecryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron safe storage failed to decrypt a string.";
}
}
export interface ElectronSafeStorageShape {
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
ElectronSafeStorageShape
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
});
export const layer = Layer.succeed(ElectronSafeStorage, make);
@@ -0,0 +1,59 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
const { openExternalMock, writeTextMock } = vi.hoisted(() => ({
openExternalMock: vi.fn(),
writeTextMock: vi.fn(),
}));
vi.mock("electron", () => ({
shell: {
openExternal: openExternalMock,
},
clipboard: {
writeText: writeTextMock,
},
}));
import * as ElectronShell from "./ElectronShell.ts";
describe("ElectronShell", () => {
beforeEach(() => {
openExternalMock.mockReset();
writeTextMock.mockReset();
});
it.effect("opens safe external URLs", () =>
Effect.gen(function* () {
openExternalMock.mockResolvedValue(undefined);
const electronShell = yield* ElectronShell.ElectronShell;
const result = yield* electronShell.openExternal("https://example.com/path");
assert.equal(result, true);
assert.deepEqual(openExternalMock.mock.calls, [["https://example.com/path"]]);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("does not open unsafe external URLs", () =>
Effect.gen(function* () {
const electronShell = yield* ElectronShell.ElectronShell;
const result = yield* electronShell.openExternal("file:///etc/passwd");
assert.equal(result, false);
assert.equal(openExternalMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("returns false when Electron rejects openExternal", () =>
Effect.gen(function* () {
openExternalMock.mockRejectedValue(new Error("open failed"));
const electronShell = yield* ElectronShell.ElectronShell;
const result = yield* electronShell.openExternal("https://example.com/path");
assert.equal(result, false);
}).pipe(Effect.provide(ElectronShell.layer)),
);
});
@@ -0,0 +1,50 @@
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 SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
return Option.none();
}
try {
const url = new URL(rawUrl);
return SAFE_EXTERNAL_PROTOCOLS.has(url.protocol) ? Option.some(url.href) : Option.none();
} catch {
return Option.none();
}
}
export interface ElectronShellShape {
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
onSome: (externalUrl) =>
Effect.promise(() =>
Electron.shell.openExternal(externalUrl).then(
() => true,
() => false,
),
),
}),
copyText: (text) =>
Effect.sync(() => {
Electron.clipboard.writeText(text);
}),
});
export const layer = Layer.succeed(ElectronShell, make);
@@ -0,0 +1,52 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
onMock: vi.fn(),
removeListenerMock: vi.fn(),
themeState: {
shouldUseDarkColors: true,
themeSource: "system",
},
}));
vi.mock("electron", () => ({
nativeTheme: {
get shouldUseDarkColors() {
return themeState.shouldUseDarkColors;
},
set themeSource(value: string) {
themeState.themeSource = value;
},
on: onMock,
removeListener: removeListenerMock,
},
}));
import * as ElectronTheme from "./ElectronTheme.ts";
describe("ElectronTheme", () => {
beforeEach(() => {
onMock.mockClear();
removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true;
themeState.themeSource = "system";
});
it.effect("scopes native theme update listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
yield* Effect.scoped(
Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
yield* electronTheme.onUpdated(listener);
}),
);
assert.deepEqual(onMock.mock.calls, [["updated", listener]]);
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
});
@@ -0,0 +1,40 @@
import type { DesktopTheme } from "@t3tools/contracts";
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 ElectronThemeShape {
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.suspend(() => {
Electron.nativeTheme.themeSource = theme;
return Effect.void;
}),
onUpdated: (listener) =>
Effect.acquireRelease(
Effect.suspend(() => {
Electron.nativeTheme.on("updated", listener);
return Effect.void;
}),
() =>
Effect.suspend(() => {
Electron.nativeTheme.removeListener("updated", listener);
return Effect.void;
}),
),
});
export const layer = Layer.succeed(ElectronTheme, make);
@@ -0,0 +1,79 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vitest";
const { autoUpdaterMock } = vi.hoisted(() => ({
autoUpdaterMock: {
allowDowngrade: false,
allowPrerelease: false,
autoDownload: true,
autoInstallOnAppQuit: true,
channel: "latest",
disableDifferentialDownload: false,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve([])),
on: vi.fn(),
quitAndInstall: vi.fn(),
removeListener: vi.fn(),
setFeedURL: vi.fn(),
},
}));
vi.mock("electron-updater", () => ({
autoUpdater: autoUpdaterMock,
}));
import * as ElectronUpdater from "./ElectronUpdater.ts";
describe("ElectronUpdater", () => {
beforeEach(() => {
autoUpdaterMock.allowDowngrade = false;
autoUpdaterMock.allowPrerelease = false;
autoUpdaterMock.autoDownload = true;
autoUpdaterMock.autoInstallOnAppQuit = true;
autoUpdaterMock.channel = "latest";
autoUpdaterMock.disableDifferentialDownload = false;
autoUpdaterMock.checkForUpdates.mockClear();
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
autoUpdaterMock.downloadUpdate.mockClear();
autoUpdaterMock.downloadUpdate.mockImplementation(() => Promise.resolve([]));
autoUpdaterMock.on.mockClear();
autoUpdaterMock.quitAndInstall.mockClear();
autoUpdaterMock.removeListener.mockClear();
autoUpdaterMock.setFeedURL.mockClear();
});
it.effect("scopes updater event listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
yield* Effect.scoped(
Effect.gen(function* () {
const updater = yield* ElectronUpdater.ElectronUpdater;
yield* updater.on("update-available", listener);
}),
);
assert.deepEqual(autoUpdaterMock.on.mock.calls, [["update-available", listener]]);
assert.deepEqual(autoUpdaterMock.removeListener.mock.calls, [["update-available", listener]]);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("wraps rejected update checks in the method-specific typed error", () =>
Effect.gen(function* () {
const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
const exit = yield* Effect.exit(updater.checkForUpdates);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
@@ -0,0 +1,139 @@
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 Scope from "effect/Scope";
import { autoUpdater } from "electron-updater";
type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
"ElectronUpdaterCheckForUpdatesError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
"ElectronUpdaterDownloadUpdateError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
"ElectronUpdaterQuitAndInstallError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to quit and install the update.";
}
}
export type ElectronUpdaterError =
| ElectronUpdaterCheckForUpdatesError
| ElectronUpdaterDownloadUpdateError
| ElectronUpdaterQuitAndInstallError;
export interface ElectronUpdaterShape {
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
setFeedURL: (options) =>
Effect.suspend(() => {
autoUpdater.setFeedURL(options);
return Effect.void;
}),
setAutoDownload: (value) =>
Effect.suspend(() => {
autoUpdater.autoDownload = value;
return Effect.void;
}),
setAutoInstallOnAppQuit: (value) =>
Effect.suspend(() => {
autoUpdater.autoInstallOnAppQuit = value;
return Effect.void;
}),
setChannel: (channel) =>
Effect.suspend(() => {
autoUpdater.channel = channel;
return Effect.void;
}),
setAllowPrerelease: (value) =>
Effect.suspend(() => {
autoUpdater.allowPrerelease = value;
return Effect.void;
}),
allowDowngrade: Effect.sync(() => autoUpdater.allowDowngrade),
setAllowDowngrade: (value) =>
Effect.suspend(() => {
autoUpdater.allowDowngrade = value;
return Effect.void;
}),
setDisableDifferentialDownload: (value) =>
Effect.suspend(() => {
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
checkForUpdates: Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
}).pipe(Effect.asVoid),
downloadUpdate: Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
}).pipe(Effect.asVoid),
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
}),
on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as {
on: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
};
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);
},
} satisfies ElectronUpdaterShape);
@@ -0,0 +1,51 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type * as Electron from "electron";
import { beforeEach, vi } from "vitest";
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
getAllWindowsMock: vi.fn(),
}));
vi.mock("electron", () => ({
app: {
focus: appFocusMock,
},
BrowserWindow: {
getAllWindows: getAllWindowsMock,
},
}));
import * as ElectronWindow from "./ElectronWindow.ts";
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
return {
isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow;
}
describe("ElectronWindow", () => {
beforeEach(() => {
appFocusMock.mockReset();
getAllWindowsMock.mockReset();
});
it.effect("skips windows destroyed before appearance sync runs", () =>
Effect.gen(function* () {
const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = [];
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.syncAllAppearance((window) =>
Effect.sync(() => {
syncedWindows.push(window);
}),
);
assert.deepEqual(syncedWindows, [liveWindow]);
}).pipe(Effect.provide(ElectronWindow.layer)),
);
});
+135
View File
@@ -0,0 +1,135 @@
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 * as Electron from "electron";
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to create Electron BrowserWindow.";
}
}
export interface ElectronWindowShape {
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
) {}
const make = Effect.gen(function* () {
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const liveMain = Ref.get(mainWindowRef).pipe(
Effect.map(Option.filter((value) => !value.isDestroyed())),
);
const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain;
if (Option.isSome(main)) {
return main;
}
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
);
});
const focusedMainOrFirst = Effect.sync(() =>
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
),
).pipe(
Effect.flatMap((focused) =>
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
),
);
return ElectronWindow.of({
create: (options) =>
Effect.try({
try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ cause }),
}),
main: liveMain,
currentMainOrFirst,
focusedMainOrFirst,
setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
clearMain: (window) =>
Ref.update(mainWindowRef, (current) => {
if (Option.isNone(current)) {
return current;
}
if (Option.isSome(window) && current.value !== window.value) {
return current;
}
return Option.none();
}),
reveal: (window) =>
Effect.sync(() => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (process.platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) {
continue;
}
window.webContents.send(channel, ...args);
}
}),
destroyAll: Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
window.destroy();
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) {
const windows = Electron.BrowserWindow.getAllWindows();
for (const window of windows) {
if (window.isDestroyed()) {
continue;
}
yield* sync(window);
}
}),
});
});
export const layer = Layer.effect(ElectronWindow, make);
+221
View File
@@ -0,0 +1,221 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
export interface DesktopIpcInvokeEvent {}
export interface DesktopIpcSyncEvent {
returnValue: unknown;
}
export type DesktopIpcHandleListener = (
event: DesktopIpcInvokeEvent,
raw: unknown,
) => unknown | Promise<unknown>;
export type DesktopIpcSyncListener = (event: DesktopIpcSyncEvent) => void;
export interface DesktopIpcMain {
removeHandler(channel: string): void;
handle(channel: string, listener: DesktopIpcHandleListener): void;
removeAllListeners(channel: string): void;
on(channel: string, listener: DesktopIpcSyncListener): void;
}
export interface DesktopIpcMethod<E, R> {
readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
}
export interface DesktopSyncIpcMethod<E, R> {
readonly channel: string;
readonly handler: () => Effect.Effect<unknown, E, R>;
}
export interface DesktopIpcShape {
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
DesktopIpc.of({
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
channel,
handler,
}: DesktopIpcMethod<E, R>) {
yield* Effect.annotateCurrentSpan({ channel });
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
}),
() => Effect.sync(() => ipcMain.removeHandler(channel)),
);
}),
handleSync: Effect.fn("desktop.ipc.registerSync")(function* <E, R>({
channel,
handler,
}: DesktopSyncIpcMethod<E, R>) {
yield* Effect.annotateCurrentSpan({ channel });
const context = yield* Effect.context<R>();
const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
);
});
}),
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
);
}),
});
/**
* Convenience helpers for creating IPC methods
*/
export interface DesktopIpcMethodRegistration<
Payload,
EncodedPayload,
Result,
EncodedResult,
E,
R,
PayloadDecodingServices = never,
PayloadEncodingServices = never,
ResultDecodingServices = never,
ResultEncodingServices = never,
> {
readonly channel: string;
readonly payload: Schema.Codec<
Payload,
EncodedPayload,
PayloadDecodingServices,
PayloadEncodingServices
>;
readonly result: Schema.Codec<
Result,
EncodedResult,
ResultDecodingServices,
ResultEncodingServices
>;
readonly handler: (input: Payload) => Effect.Effect<Result, E, R>;
}
export const makeIpcMethod = <
Payload,
EncodedPayload,
Result,
EncodedResult,
E,
R,
PayloadDecodingServices = never,
PayloadEncodingServices = never,
ResultDecodingServices = never,
ResultEncodingServices = never,
>(
method: DesktopIpcMethodRegistration<
Payload,
EncodedPayload,
Result,
EncodedResult,
E,
R,
PayloadDecodingServices,
PayloadEncodingServices,
ResultDecodingServices,
ResultEncodingServices
>,
): DesktopIpcMethod<
E | Schema.SchemaError,
R | PayloadDecodingServices | ResultEncodingServices
> => {
const decode = Schema.decodeUnknownEffect(method.payload);
const encode = Schema.encodeUnknownEffect(method.result);
return {
channel: method.channel,
handler: (raw) =>
decode(raw).pipe(
Effect.flatMap(method.handler),
Effect.flatMap(encode),
Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
),
};
};
export interface DesktopSyncIpcMethodRegistration<
Result,
EncodedResult,
E,
R,
ResultDecodingServices = never,
ResultEncodingServices = never,
> {
readonly channel: string;
readonly result: Schema.Codec<
Result,
EncodedResult,
ResultDecodingServices,
ResultEncodingServices
>;
readonly handler: () => Effect.Effect<Result, E, R>;
}
export const makeSyncIpcMethod = <
Result,
EncodedResult,
E,
R,
ResultDecodingServices = never,
ResultEncodingServices = never,
>(
method: DesktopSyncIpcMethodRegistration<
Result,
EncodedResult,
E,
R,
ResultDecodingServices,
ResultEncodingServices
>,
): DesktopSyncIpcMethod<E | Schema.SchemaError, R | ResultEncodingServices> => {
const encode = Schema.encodeUnknownEffect(method.result);
return {
channel: method.channel,
handler: () =>
method
.handler()
.pipe(
Effect.flatMap(encode),
Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
),
};
};
@@ -0,0 +1,84 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
setServerExposureMode,
setTailscaleServeEnabled,
} from "./methods/serverExposure.ts";
import {
bootstrapSshBearerSession,
disconnectSshEnvironment,
discoverSshHosts,
ensureSshEnvironment,
fetchSshEnvironmentDescriptor,
fetchSshSessionState,
issueSshWebSocketToken,
resolveSshPasswordPrompt,
} from "./methods/sshEnvironment.ts";
import {
checkForUpdate,
downloadUpdate,
getUpdateState,
installUpdate,
setUpdateChannel,
} from "./methods/updates.ts";
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
setTheme,
showContextMenu,
} from "./methods/window.ts";
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
yield* ipc.handle(disconnectSshEnvironment);
yield* ipc.handle(fetchSshEnvironmentDescriptor);
yield* ipc.handle(bootstrapSshBearerSession);
yield* ipc.handle(fetchSshSessionState);
yield* ipc.handle(issueSshWebSocketToken);
yield* ipc.handle(resolveSshPasswordPrompt);
yield* ipc.handle(getServerExposureState);
yield* ipc.handle(setServerExposureMode);
yield* ipc.handle(setTailscaleServeEnabled);
yield* ipc.handle(getAdvertisedEndpoints);
yield* ipc.handle(pickFolder);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
+35
View File
@@ -0,0 +1,35 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
export const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
export const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
export const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
export const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
export const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
export const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
@@ -0,0 +1,28 @@
import { ClientSettingsSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getClientSettings = makeIpcMethod({
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(ClientSettingsSchema),
handler: Effect.fn("desktop.ipc.clientSettings.get")(function* () {
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
return Option.getOrNull(yield* clientSettings.get);
}),
});
export const setClientSettings = makeIpcMethod({
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
payload: ClientSettingsSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.clientSettings.set")(function* (settings) {
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
yield* clientSettings.set(settings);
}),
});
@@ -0,0 +1,76 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -0,0 +1,69 @@
import {
AdvertisedEndpoint,
DesktopServerExposureModeSchema,
DesktopServerExposureStateSchema,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SetTailscaleServeEnabledInput = Schema.Struct({
enabled: Schema.Boolean,
port: Schema.optionalKey(Schema.Number),
});
export const getServerExposureState = makeIpcMethod({
channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopServerExposureStateSchema,
handler: Effect.fn("desktop.ipc.serverExposure.getState")(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
return yield* serverExposure.getState;
}),
});
export const setServerExposureMode = makeIpcMethod({
channel: IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL,
payload: DesktopServerExposureModeSchema,
result: DesktopServerExposureStateSchema,
handler: Effect.fn("desktop.ipc.serverExposure.setMode")(function* (mode) {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const change = yield* serverExposure.setMode(mode);
if (change.requiresRelaunch) {
yield* lifecycle.relaunch(`serverExposureMode=${mode}`);
}
return change.state;
}),
});
export const setTailscaleServeEnabled = makeIpcMethod({
channel: IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL,
payload: SetTailscaleServeEnabledInput,
result: DesktopServerExposureStateSchema,
handler: Effect.fn("desktop.ipc.serverExposure.setTailscaleServeEnabled")(function* (input) {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const change = yield* serverExposure.setTailscaleServeEnabled(input);
if (change.requiresRelaunch) {
yield* lifecycle.relaunch(
change.state.tailscaleServeEnabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled",
);
}
return change.state;
}),
});
export const getAdvertisedEndpoints = makeIpcMethod({
channel: IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(AdvertisedEndpoint),
handler: Effect.fn("desktop.ipc.serverExposure.getAdvertisedEndpoints")(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
return yield* serverExposure.getAdvertisedEndpoints;
}),
});
@@ -0,0 +1,127 @@
import {
DesktopDiscoveredSshHostSchema,
DesktopSshBearerBootstrapInputSchema,
DesktopSshBearerRequestInputSchema,
DesktopSshEnvironmentEnsureInputSchema,
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshEnvironmentTargetSchema,
DesktopSshHttpBaseUrlInputSchema,
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopSshRemoteApi from "../../ssh/DesktopSshRemoteApi.ts";
export const discoverSshHosts = makeIpcMethod({
channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(DesktopDiscoveredSshHostSchema),
handler: Effect.fn("desktop.ipc.sshEnvironment.discoverHosts")(function* () {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.discoverHosts();
}),
});
export const ensureSshEnvironment = makeIpcMethod({
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentEnsureInputSchema,
result: DesktopSshEnvironmentEnsureResultSchema,
handler: Effect.fn("desktop.ipc.sshEnvironment.ensureEnvironment")(function* ({
target,
options,
}) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
Effect.catch((error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed({
type: DesktopSshPasswordPromptCancelledType,
message: error.message,
})
: Effect.fail(error),
),
);
}),
});
export const disconnectSshEnvironment = makeIpcMethod({
channel: IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentTargetSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.sshEnvironment.disconnectEnvironment")(function* (target) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
yield* sshEnvironment.disconnectEnvironment(target);
}),
});
export const fetchSshEnvironmentDescriptor = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema,
result: ExecutionEnvironmentDescriptor,
handler: Effect.fn("desktop.ipc.sshEnvironment.fetchDescriptor")(function* ({ httpBaseUrl }) {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
return yield* remoteApi.fetchEnvironmentDescriptor({ httpBaseUrl });
}),
});
export const bootstrapSshBearerSession = makeIpcMethod({
channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
payload: DesktopSshBearerBootstrapInputSchema,
result: AuthBearerBootstrapResult,
handler: Effect.fn("desktop.ipc.sshEnvironment.bootstrapBearerSession")(function* ({
httpBaseUrl,
credential,
}) {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
return yield* remoteApi.bootstrapBearerSession({ httpBaseUrl, credential });
}),
});
export const fetchSshSessionState = makeIpcMethod({
channel: IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthSessionState,
handler: Effect.fn("desktop.ipc.sshEnvironment.fetchSessionState")(function* ({
httpBaseUrl,
bearerToken,
}) {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
return yield* remoteApi.fetchSessionState({ httpBaseUrl, bearerToken });
}),
});
export const issueSshWebSocketToken = makeIpcMethod({
channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
payload: DesktopSshBearerRequestInputSchema,
result: AuthWebSocketTokenResult,
handler: Effect.fn("desktop.ipc.sshEnvironment.issueWebSocketToken")(function* ({
httpBaseUrl,
bearerToken,
}) {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
return yield* remoteApi.issueWebSocketToken({ httpBaseUrl, bearerToken });
}),
});
export const resolveSshPasswordPrompt = makeIpcMethod({
channel: IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
payload: DesktopSshPasswordPromptResolutionInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.sshEnvironment.resolvePasswordPrompt")(function* ({
requestId,
password,
}) {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
yield* prompts.resolve({ requestId, password });
}),
});
+62
View File
@@ -0,0 +1,62 @@
import {
DesktopUpdateActionResultSchema,
DesktopUpdateChannelSchema,
DesktopUpdateCheckResultSchema,
DesktopUpdateStateSchema,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as DesktopUpdates from "../../updates/DesktopUpdates.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getUpdateState = makeIpcMethod({
channel: IpcChannels.UPDATE_GET_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateStateSchema,
handler: Effect.fn("desktop.ipc.updates.getState")(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
return yield* updates.getState;
}),
});
export const setUpdateChannel = makeIpcMethod({
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
payload: DesktopUpdateChannelSchema,
result: DesktopUpdateStateSchema,
handler: Effect.fn("desktop.ipc.updates.setChannel")(function* (channel) {
const updates = yield* DesktopUpdates.DesktopUpdates;
return yield* updates.setChannel(channel);
}),
});
export const downloadUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_DOWNLOAD_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
handler: Effect.fn("desktop.ipc.updates.download")(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
return yield* updates.download;
}),
});
export const installUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateActionResultSchema,
handler: Effect.fn("desktop.ipc.updates.install")(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
return yield* updates.install;
}),
});
export const checkForUpdate = makeIpcMethod({
channel: IpcChannels.UPDATE_CHECK_CHANNEL,
payload: Schema.Void,
result: DesktopUpdateCheckResultSchema,
handler: Effect.fn("desktop.ipc.updates.check")(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
return yield* updates.check("web-ui");
}),
});
+135
View File
@@ -0,0 +1,135 @@
import {
ContextMenuItemSchema,
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickFolderOptionsSchema,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
y: Schema.Number,
});
const ContextMenuInput = Schema.Struct({
items: Schema.Array(ContextMenuItemSchema),
position: Schema.optionalKey(ContextMenuPosition),
});
function toWebSocketBaseUrl(httpBaseUrl: URL): string {
const url = new URL(httpBaseUrl.href);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
return url.href;
}
export const getAppBranding = makeSyncIpcMethod({
channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
result: Schema.NullOr(DesktopAppBrandingSchema),
handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.branding;
}),
});
export const getLocalEnvironmentBootstrap = makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const config = yield* backendManager.currentConfig;
return Option.match(config, {
onNone: () => null,
onSome: ({ bootstrap, httpBaseUrl }) => ({
label: "Local environment",
httpBaseUrl: httpBaseUrl.href,
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
...(bootstrap.desktopBootstrapToken
? { bootstrapToken: bootstrap.desktopBootstrapToken }
: {}),
}),
});
}),
});
export const pickFolder = makeIpcMethod({
channel: IpcChannels.PICK_FOLDER_CHANNEL,
payload: Schema.UndefinedOr(PickFolderOptionsSchema),
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const selectedPath = yield* dialog.pickFolder({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: environment.resolvePickFolderDefaultPath(options),
});
return Option.getOrNull(selectedPath);
}),
});
export const confirm = makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
return yield* electronWindow.focusedMainOrFirst.pipe(
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
);
}),
});
export const setTheme = makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
const electronTheme = yield* ElectronTheme.ElectronTheme;
yield* electronTheme.setSource(theme);
}),
});
export const showContextMenu = makeIpcMethod({
channel: IpcChannels.CONTEXT_MENU_CHANNEL,
payload: ContextMenuInput,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = yield* electronWindow.focusedMainOrFirst;
if (Option.isNone(window)) {
return null;
}
const selectedItemId = yield* electronMenu.showContextMenu({
window: window.value,
items: input.items,
position: Option.fromNullishOr(input.position),
});
return Option.getOrNull(selectedItemId);
}),
});
export const openExternal = makeIpcMethod({
channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
const shell = yield* ElectronShell.ElectronShell;
return yield* shell.openExternal(url);
}),
});
+138 -1400
View File
File diff suppressed because it is too large. Load diff
+103 -27
View File
@@ -1,51 +1,127 @@
import { contextBridge, ipcRenderer } from "electron";
import type { DesktopBridge } from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
import * as IpcChannels from "./ipc/channels.ts";
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
result !== null &&
"type" in result &&
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
) {
const message =
"message" in result && typeof result.message === "string"
? result.message
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => {
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
return typeof result === "string" ? result : null;
getAppBranding: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
await ipcRenderer.invoke(IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL, {
target,
...(options === undefined ? {} : { options }),
}),
),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, { httpBaseUrl }),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
ipcRenderer.invoke(IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, {
httpBaseUrl,
credential,
}),
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL, { httpBaseUrl, bearerToken }),
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, { httpBaseUrl, bearerToken }),
onSshPasswordPrompt: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
if (typeof request !== "object" || request === null) return;
listener(request as Parameters<typeof listener>[0]);
};
ipcRenderer.on(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
};
},
resolveSshPasswordPrompt: (requestId, password) =>
ipcRenderer.invoke(IpcChannels.RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, { requestId, password }),
getServerExposureState: () => ipcRenderer.invoke(IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) =>
ipcRenderer.invoke(IpcChannels.SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
items,
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
listener(action);
};
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
ipcRenderer.on(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) =>
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
checkForUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
if (typeof state !== "object" || state === null) return;
listener(state as Parameters<typeof listener>[0]);
};
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
ipcRenderer.on(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
};
},
} satisfies DesktopBridge);
-74
View File
@@ -1,74 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { afterEach, describe, expect, it } from "vitest";
const tempRoots: string[] = [];
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
tempRoots.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempRoots.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("RotatingFileSink", () => {
it("rotates when writes exceed max bytes", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 10,
maxFiles: 3,
});
sink.write("12345");
sink.write("67890");
sink.write("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
});
it("retains only maxFiles backups", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "server-child.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 4,
maxFiles: 2,
});
sink.write("aaaa");
sink.write("bbbb");
sink.write("cccc");
sink.write("dddd");
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
});
it("prunes stale backups above maxFiles on startup", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 16,
maxFiles: 2,
});
sink.write("hello");
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
});
});
-49
View File
@@ -1,49 +0,0 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true);
});
it("detects native Apple Silicon builds", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "arm64",
runningUnderArm64Translation: false,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "arm64",
runningUnderArm64Translation: false,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false);
});
it("passes through non-mac builds without translation", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "linux",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
});
});
});
-39
View File
@@ -1,39 +0,0 @@
import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts";
interface ResolveDesktopRuntimeInfoInput {
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly runningUnderArm64Translation: boolean;
}
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
return "other";
}
export function resolveDesktopRuntimeInfo(
input: ResolveDesktopRuntimeInfoInput,
): 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,
};
}
export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
@@ -0,0 +1,284 @@
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 * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_DESKTOP_SETTINGS,
resolveDefaultDesktopSettings,
type DesktopSettings as DesktopSettingsValue,
} from "./DesktopAppSettings.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
});
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
const encodeDesktopSettingsPatch = Schema.encodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
function makeEnvironmentLayer(baseDir: string, appVersion = "0.0.17") {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion,
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
}
const withSettings = <A, E, R>(
effect: Effect.Effect<
A,
E,
R | DesktopAppSettings.DesktopAppSettings | DesktopEnvironment.DesktopEnvironment
>,
options?: { readonly appVersion?: string },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-settings-test-",
});
return yield* effect.pipe(
Effect.provide(
DesktopAppSettings.layer.pipe(
Layer.provideMerge(makeEnvironmentLayer(baseDir, options?.appVersion)),
Layer.provideMerge(NodeServices.layer),
),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
function writeSettingsPatch(patch: typeof DesktopSettingsPatch.Type) {
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const encoded = yield* encodeDesktopSettingsPatch(patch);
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.desktopSettingsPath, `${encoded}\n`);
});
}
describe("DesktopSettings", () => {
it.effect("loads defaults when no settings file exists", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
assert.deepEqual(yield* settings.get, DEFAULT_DESKTOP_SETTINGS);
}),
),
);
it("defaults packaged nightly builds to the nightly update channel", () => {
assert.deepEqual(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
} satisfies DesktopSettingsValue);
});
it.effect("loads persisted settings and applies semantic updates", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
assert.deepEqual(yield* settings.load, {
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
} satisfies DesktopSettingsValue);
const exposure = yield* settings.setServerExposureMode("local-only");
assert.isTrue(exposure.changed);
assert.equal(exposure.settings.serverExposureMode, "local-only");
const tailscale = yield* settings.setTailscaleServe({
enabled: true,
port: Option.some(9443),
});
assert.isTrue(tailscale.changed);
assert.equal(tailscale.settings.tailscaleServePort, 9443);
const updateChannel = yield* settings.setUpdateChannel("nightly");
assert.isTrue(updateChannel.changed);
assert.equal(updateChannel.settings.updateChannel, "nightly");
assert.equal(updateChannel.settings.updateChannelConfiguredByUser, true);
}),
),
);
it.effect("does not persist no-op semantic updates", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const exposure = yield* settings.setServerExposureMode("local-only");
assert.isFalse(exposure.changed);
const tailscale = yield* settings.setTailscaleServe({
enabled: false,
port: Option.none(),
});
assert.isFalse(tailscale.changed);
const updateChannel = yield* settings.setUpdateChannel("latest");
assert.isFalse(updateChannel.changed);
assert.equal(updateChannel.settings.updateChannelConfiguredByUser, false);
}),
),
);
it.effect("falls back to defaults when the settings file is malformed", () =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.desktopSettingsPath, "{not-json");
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
}),
),
);
it.effect("loads lenient persisted desktop settings JSON", () =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{
// JSONC-style comments and trailing commas match server settings parsing.
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
}\n`,
);
assert.deepEqual(yield* settings.load, {
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
} satisfies DesktopSettingsValue);
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.setServerExposureMode("network-accessible");
const persisted = yield* decodeDesktopSettingsPatch(
yield* fileSystem.readFileString(environment.desktopSettingsPath),
);
assert.deepEqual(persisted, {
serverExposureMode: "network-accessible",
} satisfies typeof DesktopSettingsPatch.Type);
}),
),
);
it.effect("migrates legacy implicit update channels to the runtime default", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
serverExposureMode: "local-only",
updateChannel: "latest",
});
assert.deepEqual(yield* settings.load, {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
} satisfies DesktopSettingsValue);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
),
);
it.effect("preserves explicit stable update channel on nightly builds", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
serverExposureMode: "local-only",
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
assert.deepEqual(yield* settings.load, {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
} satisfies DesktopSettingsValue);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
),
);
it.effect("normalizes invalid persisted Tailscale Serve ports", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
tailscaleServeEnabled: true,
tailscaleServePort: 0,
});
assert.deepEqual(yield* settings.load, {
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
} satisfies DesktopSettingsValue);
}),
),
);
});
@@ -0,0 +1,324 @@
import {
DesktopServerExposureModeSchema,
DesktopUpdateChannelSchema,
type DesktopServerExposureMode,
type DesktopUpdateChannel,
} from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
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 Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export interface DesktopSettingsChange {
readonly settings: DesktopSettings;
readonly changed: boolean;
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
const DesktopSettingsDocument = Schema.Struct({
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
});
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
settings,
changed,
});
export class DesktopSettingsWriteError extends Data.TaggedError("DesktopSettingsWriteError")<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop settings: ${this.cause.message}`;
}
}
export interface DesktopAppSettingsShape {
readonly load: Effect.Effect<DesktopSettings>;
readonly get: Effect.Effect<DesktopSettings>;
readonly setServerExposureMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setTailscaleServe: (input: {
readonly enabled: boolean;
readonly port: Option.Option<number>;
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
}
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
DesktopAppSettingsShape
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
};
}
function normalizeTailscaleServePort(value: unknown): number {
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
? value
: DEFAULT_TAILSCALE_SERVE_PORT;
}
function normalizeDesktopSettingsDocument(
parsed: DesktopSettingsDocument,
appVersion: string,
): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
updateChannel: updateChannelConfiguredByUser
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
};
}
function toDesktopSettingsDocument(
settings: DesktopSettings,
defaults: DesktopSettings,
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.serverExposureMode !== defaults.serverExposureMode) {
document.serverExposureMode = settings.serverExposureMode;
}
if (settings.tailscaleServeEnabled !== defaults.tailscaleServeEnabled) {
document.tailscaleServeEnabled = settings.tailscaleServeEnabled;
}
if (settings.tailscaleServePort !== defaults.tailscaleServePort) {
document.tailscaleServePort = settings.tailscaleServePort;
}
if (settings.updateChannel !== defaults.updateChannel) {
document.updateChannel = settings.updateChannel;
}
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
}
return document;
}
function setServerExposureMode(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
): DesktopSettings {
return settings.serverExposureMode === requestedMode
? settings
: {
...settings,
serverExposureMode: requestedMode,
};
}
function setTailscaleServe(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port: Option.Option<number> },
): DesktopSettings {
const port = Option.match(input.port, {
onNone: () => settings.tailscaleServePort,
onSome: normalizeTailscaleServePort,
});
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
? settings
: {
...settings,
tailscaleServeEnabled: input.enabled,
tailscaleServePort: port,
};
}
function setUpdateChannel(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
): DesktopSettings {
return settings.updateChannel === requestedChannel
? settings
: {
...settings,
updateChannel: requestedChannel,
updateChannelConfiguredByUser: true,
};
}
function readSettings(
fileSystem: FileSystem.FileSystem,
settingsPath: string,
appVersion: string,
): Effect.Effect<DesktopSettings> {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
return fileSystem.readFileString(settingsPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(defaultSettings),
onSome: (raw) =>
decodeDesktopSettingsJson(raw).pipe(
Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
Effect.catch(() => Effect.succeed(defaultSettings)),
),
}),
),
);
}
const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly settingsPath: string;
readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.settingsPath);
});
export const layer = Layer.effect(
DesktopAppSettings,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
const nextSettings = update(settings);
if (nextSettings === settings) {
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
});
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: Effect.gen(function* () {
const settings = yield* readSettings(
fileSystem,
environment.desktopSettingsPath,
environment.appVersion,
);
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
}).pipe(Effect.withSpan("desktop.settings.load")),
setServerExposureMode: (mode) =>
persist((settings) => setServerExposureMode(settings, mode)).pipe(
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
),
setTailscaleServe: (input) =>
persist((settings) => setTailscaleServe(settings, input)).pipe(
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
),
setUpdateChannel: (channel) =>
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
});
}),
);
export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
Layer.effect(
DesktopAppSettings,
Effect.gen(function* () {
const settingsRef = yield* SynchronizedRef.make(initialSettings);
const update = (f: (settings: DesktopSettings) => DesktopSettings) =>
SynchronizedRef.modify(settingsRef, (settings) => {
const nextSettings = f(settings);
return [
{
settings: nextSettings,
changed: nextSettings !== settings,
},
nextSettings,
] as const;
});
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: SynchronizedRef.get(settingsRef),
setServerExposureMode: (mode) =>
update((settings) => setServerExposureMode(settings, mode)),
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
});
}),
);
@@ -0,0 +1,185 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
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 Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
const decodeRecordJson = Schema.decodeEffect(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
);
function makeLayer(baseDir: string) {
const environmentLayer = DesktopEnvironment.layer({
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 })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(NodeServices.layer),
);
}
const withClientSettings = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopClientSettings.DesktopClientSettings>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-client-settings-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopClientSettings", () => {
it.effect("returns none when no client settings file exists", () =>
withClientSettings(
Effect.gen(function* () {
const settings = yield* DesktopClientSettings.DesktopClientSettings;
assert.isTrue(Option.isNone(yield* settings.get));
}),
),
);
it.effect("persists and reloads client settings", () =>
withClientSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
yield* settings.set(clientSettings);
assert.deepEqual(yield* settings.get, Option.some(clientSettings));
assert.deepEqual(
yield* decodeClientSettingsJson(
yield* fileSystem.readFileString(environment.clientSettingsPath),
),
clientSettings,
);
assert.isFalse(
Object.hasOwn(
yield* decodeRecordJson(
yield* fileSystem.readFileString(environment.clientSettingsPath),
),
"settings",
),
);
}),
),
);
it.effect("loads lenient direct client settings documents", () =>
withClientSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.clientSettingsPath,
`{
// Matches server settings parsing.
"timestampFormat": "24-hour",
}\n`,
);
const persisted = yield* settings.get;
assert.isTrue(Option.isSome(persisted));
if (Option.isSome(persisted)) {
assert.equal(persisted.value.timestampFormat, "24-hour");
}
}),
),
);
it.effect("loads legacy wrapped client settings documents", () =>
withClientSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.clientSettingsPath,
`{
"settings": {
"timestampFormat": "12-hour"
}
}\n`,
);
const persisted = yield* settings.get;
assert.isTrue(Option.isSome(persisted));
if (Option.isSome(persisted)) {
assert.equal(persisted.value.timestampFormat, "12-hour");
}
}),
),
);
it.effect("loads defaults from empty client settings documents", () =>
withClientSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.clientSettingsPath, "{}\n");
assert.deepEqual(yield* settings.get, Option.some(yield* decodeClientSettingsJson("{}")));
}),
),
);
it.effect("treats malformed client settings documents as absent", () =>
withClientSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.clientSettingsPath, "{not-json");
assert.isTrue(Option.isNone(yield* settings.get));
}),
),
);
});
@@ -0,0 +1,128 @@
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
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 Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
const ClientSettingsDocumentSchema = Schema.Struct({
settings: ClientSettingsSchema,
});
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
LegacyClientSettingsDocumentJson,
);
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
export class DesktopClientSettingsWriteError extends Data.TaggedError(
"DesktopClientSettingsWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop client settings: ${this.cause.message}`;
}
}
export interface DesktopClientSettingsShape {
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
readonly set: (settings: ClientSettings) => Effect.Effect<void, DesktopClientSettingsWriteError>;
}
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
DesktopClientSettingsShape
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
const readClientSettings = (
fileSystem: FileSystem.FileSystem,
settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.catch(() => Effect.succeed(Option.none<ClientSettings>())),
),
}),
),
);
const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly settingsPath: string;
readonly settings: ClientSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.settingsPath);
});
export const layer = Layer.effect(
DesktopClientSettings,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
Effect.withSpan("desktop.clientSettings.set"),
),
});
}),
);
export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
Layer.effect(
DesktopClientSettings,
Effect.gen(function* () {
const settingsRef = yield* Ref.make(initialSettings);
return DesktopClientSettings.of({
get: Ref.get(settingsRef),
set: (settings) => Ref.set(settingsRef, Option.some(settings)),
});
}),
);
@@ -0,0 +1,344 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
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 Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "./DesktopSavedEnvironments.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({
version: Schema.Number,
records: Schema.Array(Schema.Unknown),
});
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe),
);
function makeSafeStorageLayer(input: {
readonly available: boolean;
readonly availabilityError?: unknown;
readonly encryptError?: unknown;
readonly decryptError?: unknown;
}) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable:
input.availabilityError === undefined
? Effect.succeed(input.available)
: Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageAvailabilityError({
cause: input.availabilityError,
}),
),
encryptString: (value) =>
input.encryptError === undefined
? Effect.succeed(textEncoder.encode(`enc:${value}`))
: Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageEncryptError({
cause: input.encryptError,
}),
),
decryptString: (value) => {
if (input.decryptError !== undefined) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: input.decryptError,
}),
);
}
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid secret"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
baseDir: string,
options?: {
readonly availableSecretStorage?: boolean;
readonly availabilityError?: unknown;
readonly encryptError?: unknown;
readonly decryptError?: unknown;
},
) {
const environmentLayer = DesktopEnvironment.layer({
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 })),
),
);
return DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(
makeSafeStorageLayer({
available: options?.availableSecretStorage ?? true,
availabilityError: options?.availabilityError,
encryptError: options?.encryptError,
decryptError: options?.decryptError,
}),
),
Layer.provideMerge(NodeServices.layer),
);
}
const withSavedEnvironments = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopSavedEnvironments.DesktopSavedEnvironments>,
options?: {
readonly availableSecretStorage?: boolean;
readonly availabilityError?: unknown;
readonly encryptError?: unknown;
readonly decryptError?: unknown;
},
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-saved-environments-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, options)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopSavedEnvironments", () => {
it.effect("persists and reloads saved environment metadata", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]);
const persisted = yield* decodeSavedEnvironmentRegistryDocumentProbe(
yield* fileSystem.readFileString(environment.savedEnvironmentRegistryPath),
);
assert.equal(persisted.version, 1);
assert.lengthOf(persisted.records, 1);
}),
),
);
it.effect("loads lenient saved environment registry documents", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.savedEnvironmentRegistryPath,
`{
// Same optional envelope shape as browser saved environments.
"version": 1,
"records": [
{
"environmentId": "${savedRegistryRecord.environmentId}",
"label": "Remote environment",
"httpBaseUrl": "https://remote.example.com/",
"wsBaseUrl": "wss://remote.example.com/",
"createdAt": "2026-04-09T00:00:00.000Z",
"lastConnectedAt": "2026-04-09T01:00:00.000Z",
"desktopSsh": {
"alias": "devbox",
"hostname": "devbox.example.com",
"username": "julius",
"port": 22,
},
},
],
}\n`,
);
assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]);
}),
),
);
it.effect("persists encrypted saved environment secrets when encryption is available", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
}),
);
assert.deepEqual(
yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId),
Option.some("bearer-token"),
);
}),
),
);
it.effect("returns false when writing secrets while encryption is unavailable", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
assert.isFalse(
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
}),
);
}),
{ availableSecretStorage: false },
),
);
it.effect("surfaces typed safe storage availability failures", () => {
const cause = new Error("safe storage unavailable");
return withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
const error = yield* savedEnvironments
.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
})
.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
assert.equal(error.cause, cause);
}),
{ availabilityError: cause },
);
});
it.effect("removes saved environment secrets", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeSecret(savedRegistryRecord.environmentId);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{}\n");
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats malformed saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("returns false when writing a secret without metadata", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
assert.isFalse(
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
}),
);
}),
),
);
it.effect("preserves encrypted secrets when metadata is rewritten", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]);
assert.deepEqual(
yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId),
Option.some("bearer-token"),
);
}),
),
);
});
@@ -0,0 +1,398 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
type PersistedSavedEnvironmentDesktopSsh = NonNullable<
PersistedSavedEnvironmentRecord["desktopSsh"]
>;
interface PersistedSavedEnvironmentStorageRecord extends Omit<
PersistedSavedEnvironmentRecord,
"desktopSsh"
> {
readonly desktopSsh?: PersistedSavedEnvironmentDesktopSsh;
readonly encryptedBearerToken?: string;
}
interface SavedEnvironmentRegistryDocument {
readonly version: number;
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
}
interface SavedEnvironmentRegistryStorageDocument {
readonly version?: number;
readonly records?: readonly PersistedSavedEnvironmentStorageRecord[];
}
const DesktopSshTargetSchema = Schema.Struct({
alias: Schema.String,
hostname: Schema.String,
username: Schema.NullOr(Schema.String),
port: Schema.NullOr(Schema.Number),
});
const PersistedSavedEnvironmentStorageRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
label: Schema.String,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
desktopSsh: Schema.optionalKey(DesktopSshTargetSchema),
encryptedBearerToken: Schema.optionalKey(Schema.String),
});
const SavedEnvironmentRegistryDocumentSchema = Schema.Struct({
version: Schema.optionalKey(Schema.Number),
records: Schema.optionalKey(Schema.Array(PersistedSavedEnvironmentStorageRecordSchema)),
});
const SavedEnvironmentRegistryDocumentJson = fromLenientJson(
SavedEnvironmentRegistryDocumentSchema,
);
const decodeSavedEnvironmentRegistryDocumentJson = Schema.decodeEffect(
SavedEnvironmentRegistryDocumentJson,
);
const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
SavedEnvironmentRegistryDocumentJson,
);
export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
"DesktopSavedEnvironmentsWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop saved environment secret.";
}
}
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
readonly setSecret: (input: {
readonly environmentId: string;
readonly secret: string;
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
readonly removeSecret: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
}
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
DesktopSavedEnvironmentsShape
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
function toSavedEnvironmentStorageRecord(
record: PersistedSavedEnvironmentRecord | PersistedSavedEnvironmentStorageRecord,
encryptedBearerToken: Option.Option<string>,
): PersistedSavedEnvironmentStorageRecord {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
const desktopSsh = record.desktopSsh;
if (desktopSsh) {
return Option.match(encryptedBearerToken, {
onNone: () => ({ ...nextRecord, desktopSsh }),
onSome: (value) => ({
...nextRecord,
desktopSsh,
encryptedBearerToken: value,
}),
});
}
return Option.match(encryptedBearerToken, {
onNone: () => nextRecord,
onSome: (value) => ({ ...nextRecord, encryptedBearerToken: value }),
});
}
function normalizeSavedEnvironmentRegistryDocument(
document: SavedEnvironmentRegistryStorageDocument,
): SavedEnvironmentRegistryDocument {
return {
version: document.version ?? 1,
records: document.records ?? [],
};
}
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<SavedEnvironmentRegistryDocument> {
return fileSystem.readFileString(registryPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed({ version: 1, records: [] }),
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.catch(() => Effect.succeed({ version: 1, records: [] })),
),
}),
),
);
}
const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistryDocument")(
function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.registryPath);
},
);
function preserveExistingSecrets(
currentDocument: SavedEnvironmentRegistryDocument,
records: readonly PersistedSavedEnvironmentRecord[],
): SavedEnvironmentRegistryDocument {
const encryptedBearerTokenById = new Map(
currentDocument.records.flatMap((record) =>
record.encryptedBearerToken
? [[record.environmentId, record.encryptedBearerToken] as const]
: [],
),
);
return {
version: currentDocument.version,
records: records.map((record) => {
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
return toSavedEnvironmentStorageRecord(record, Option.fromNullishOr(encryptedBearerToken));
}),
};
}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopSavedEnvironmentSecretDecodeError({ cause })),
);
}
export const layer = Layer.effect(
DesktopSavedEnvironments,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
);
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(encoded.value);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret),
);
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
found = true;
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
}),
};
if (found) {
yield* writeDocument(nextDocument);
}
return found;
}),
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
if (
!document.records.some(
(record) =>
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
});
}),
});
}),
);
export const layerTest = (input?: {
readonly records?: readonly PersistedSavedEnvironmentRecord[];
readonly secrets?: ReadonlyMap<string, string>;
}) =>
Layer.effect(
DesktopSavedEnvironments,
Effect.gen(function* () {
const recordsRef = yield* Ref.make(input?.records ?? []);
const secretsRef = yield* Ref.make(new Map(input?.secrets ?? []));
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records),
getSecret: (environmentId) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
),
setSecret: ({ environmentId, secret }) =>
Ref.get(recordsRef).pipe(
Effect.flatMap((records) => {
if (!records.some((record) => record.environmentId === environmentId)) {
return Effect.succeed(false);
}
return Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.set(environmentId, secret);
return nextSecrets;
}).pipe(Effect.as(true));
}),
),
removeSecret: (environmentId) =>
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
});
}),
);
@@ -0,0 +1,232 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
const textEncoder = new TextEncoder();
function envOutput(values: Readonly<Record<string, string>>): string {
return Object.entries(values)
.flatMap(([name, value]) => [
`__T3CODE_ENV_${name}_START__`,
value,
`__T3CODE_ENV_${name}_END__`,
])
.join("\n");
}
function makeProcess(output: string): ChildProcessSpawner.ChildProcessHandle {
const stdout = output.length === 0 ? Stream.empty : Stream.make(textEncoder.encode(output));
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout,
stderr: Stream.empty,
all: stdout,
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
}
function withProcessEnv<A, E, R>(
env: NodeJS.ProcessEnv,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R> {
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = process.env;
process.env = env;
return previous;
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env = previous;
}),
);
}
function runShellEnvironment(input: {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
readonly handler: (command: ChildProcess.Command) => string;
}) {
const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
platform: input.platform,
} as DesktopEnvironment.DesktopEnvironmentShape),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
);
const program = Effect.gen(function* () {
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
yield* shellEnvironment.installIntoProcess;
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
),
),
);
return withProcessEnv(input.env, program);
}
describe("DesktopShellEnvironment", () => {
it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/Users/test/.local/bin:/usr/bin",
};
const commands: ChildProcess.Command[] = [];
yield* runShellEnvironment({
env,
platform: "darwin",
handler: (command) => {
commands.push(command);
return envOutput({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
HOMEBREW_PREFIX: "/opt/homebrew",
});
},
});
assert.equal(commands.length, 1);
assert.equal(commands[0]?._tag === "StandardCommand" ? commands[0].command : "", "/bin/zsh");
assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
assert.equal(env.HOMEBREW_PREFIX, "/opt/homebrew");
}),
);
it.effect("preserves inherited POSIX values when present", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
yield* runShellEnvironment({
env,
platform: "darwin",
handler: () =>
envOutput({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}),
});
assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
assert.equal(env.SSH_AUTH_SOCK, "/tmp/inherited.sock");
}),
);
it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}),
});
assert.equal(env.PATH, "/home/linuxbrew/.linuxbrew/bin:/usr/bin");
assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock");
}),
);
it.effect("falls back to launchctl PATH on macOS when shell probing does not return one", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/opt/homebrew/bin/nu",
PATH: "/usr/bin",
};
const commands: string[] = [];
yield* runShellEnvironment({
env,
platform: "darwin",
handler: (command) => {
if (command._tag !== "StandardCommand") return "";
commands.push(command.command);
return command.command === "/bin/launchctl" ? "/opt/homebrew/bin:/usr/bin" : "";
},
});
assert.deepEqual(commands, ["/opt/homebrew/bin/nu", "/bin/zsh", "/bin/launchctl"]);
assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin");
}),
);
it.effect("loads PowerShell profile environment on Windows", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
yield* runShellEnvironment({
env,
platform: "win32",
handler: (command) => {
if (command._tag !== "StandardCommand") return "";
const loadProfile = !command.args.includes("-NoProfile");
return loadProfile
? envOutput({
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
})
: envOutput({ PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" });
},
});
assert.equal(
env.PATH,
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
assert.equal(env.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
assert.equal(
env.FNM_MULTISHELL_PATH,
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
}),
);
});
@@ -0,0 +1,356 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
type EnvironmentPatch = Record<string, string>;
interface ShellEnvironmentConfig {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
readonly userShell: Option.Option<string>;
}
interface WindowsProbeOptions {
readonly loadProfile: boolean;
}
export interface DesktopShellEnvironmentShape {
readonly installIntoProcess: Effect.Effect<void, never>;
}
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
DesktopShellEnvironmentShape
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
Option.fromNullishOr(value).pipe(
Option.map((entry) => entry.trim()),
Option.filter((entry) => entry.length > 0),
);
const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
const normalized = entry.trim().replace(/^"+|"+$/g, "");
return platform === "win32" ? normalized.toLowerCase() : normalized;
};
const mergePaths = (
platform: NodeJS.Platform,
values: ReadonlyArray<Option.Option<string>>,
): Option.Option<string> => {
const delimiter = pathDelimiter(platform);
const entries: string[] = [];
const seen = new Set<string>();
for (const value of values) {
if (Option.isNone(value)) continue;
for (const entry of value.value.split(delimiter)) {
const trimmed = entry.trim();
if (trimmed.length === 0) continue;
const key = pathComparisonKey(trimmed, platform);
if (key.length === 0 || seen.has(key)) continue;
seen.add(key);
entries.push(trimmed);
}
}
return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
};
const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
const fallback =
config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
const seen = new Set<string>();
const candidates: string[] = [];
for (const candidate of [
trimNonEmpty(config.env.SHELL),
config.userShell,
trimNonEmpty(fallback),
]) {
if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
seen.add(candidate.value);
candidates.push(candidate.value);
}
return candidates;
};
const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
...trimNonEmpty(env.APPDATA).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\npm`],
}),
),
...trimNonEmpty(env.LOCALAPPDATA).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
}),
),
...trimNonEmpty(env.USERPROFILE).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
}),
),
];
const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
names
.map((name) => {
return [
`printf '%s\\n' '${startMarker(name)}'`,
`printenv ${name} || true`,
`printf '%s\\n' '${endMarker(name)}'`,
].join("; ");
})
.join("; ");
const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
[
"$ErrorActionPreference = 'Stop'",
...names.flatMap((name) => {
return [
`Write-Output '${startMarker(name)}'`,
`$value = [Environment]::GetEnvironmentVariable('${name}')`,
"if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
`Write-Output '${endMarker(name)}'`,
];
}),
].join("; ");
const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
const environment: EnvironmentPatch = {};
for (const name of names) {
const start = output.indexOf(startMarker(name));
if (start === -1) continue;
const valueStart = start + startMarker(name).length;
const end = output.indexOf(endMarker(name), valueStart);
if (end === -1) continue;
const value = output
.slice(valueStart, end)
.replace(/^\r?\n/, "")
.replace(/\r?\n$/, "");
if (value.length > 0) {
environment[name] = value;
}
}
return environment;
};
const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly timeout: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return yield* spawner
.string(
ChildProcess.make(input.command, input.args, {
shell: input.shell ?? false,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
}),
)
.pipe(
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.catch(() => Effect.succeed("")),
);
});
const readLoginShellEnvironment = (
shell: string,
names: ReadonlyArray<string>,
): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
names.length === 0
? Effect.succeed({})
: runCommandOutput({
command: shell,
args: ["-ilc", capturePosixEnvironmentCommand(names)],
timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath: Effect.Effect<
Option.Option<string>,
never,
ChildProcessSpawner.ChildProcessSpawner
> = runCommandOutput({
command: "/bin/launchctl",
args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT,
}).pipe(Effect.map(trimNonEmpty));
const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
function* (
names: ReadonlyArray<string>,
options: WindowsProbeOptions,
): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
if (names.length === 0) return {};
const args = [
"-NoLogo",
...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
"-NonInteractive",
"-Command",
captureWindowsEnvironmentCommand(names),
];
for (const command of WINDOWS_SHELL_CANDIDATES) {
const output = yield* runCommandOutput({
command,
args,
shell: true,
timeout: LOGIN_SHELL_TIMEOUT,
});
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
return environment;
}
}
return {};
},
);
const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
trimNonEmpty(noProfile.PATH),
readEnvPath(config.env),
]);
if (Option.isSome(mergedPath)) {
config.env.PATH = mergedPath.value;
}
if (!config.env.FNM_DIR && profile.FNM_DIR) {
config.env.FNM_DIR = profile.FNM_DIR;
}
if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
}
},
);
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
Object.assign(
shellEnvironment,
yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
);
if (shellEnvironment.PATH) break;
}
const launchctlPath =
config.platform === "darwin" && !shellEnvironment.PATH
? yield* readLaunchctlPath
: Option.none<string>();
const mergedPath = mergePaths(config.platform, [
trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
readEnvPath(config.env),
]);
if (Option.isSome(mergedPath)) {
config.env.PATH = mergedPath.value;
}
if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
for (const name of [
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
] as const) {
if (!config.env[name] && shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
},
);
const installShellEnvironment = (
config: ShellEnvironmentConfig,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
if (config.platform === "darwin" || config.platform === "linux") {
return installPosixEnvironment(config);
}
return Effect.void;
};
export const layer = Layer.effect(
DesktopShellEnvironment,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return DesktopShellEnvironment.of({
installIntoProcess: installShellEnvironment({
env: process.env,
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
),
});
}),
);
@@ -0,0 +1,118 @@
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 NetService from "@t3tools/shared/Net";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as DesktopSshEnvironment from "./DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
function makeTempHomeDir() {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-env-test-" });
});
}
describe("sshEnvironment", () => {
it("treats password prompt timeouts as cancellable authentication prompts", () => {
assert.equal(
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(
new SshPasswordPromptError({
message: "SSH authentication timed out for devbox.",
cause: new DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError({
requestId: "prompt-1",
destination: "devbox",
}),
}),
),
true,
);
});
it.effect("wires desktop host discovery through the ssh package runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const homeDir = yield* makeTempHomeDir();
const sshDir = path.join(homeDir, ".ssh");
yield* fs.makeDirectory(path.join(sshDir, "config.d"), { recursive: true });
yield* fs.writeFileString(
path.join(sshDir, "config"),
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
);
yield* fs.writeFileString(
path.join(sshDir, "config.d", "team.conf"),
[
"Host staging",
" HostName staging.example.com",
"Host *",
" ServerAliveInterval 30",
"",
].join("\n"),
);
yield* fs.writeFileString(
path.join(sshDir, "known_hosts"),
[
"known.example.com ssh-ed25519 AAAA",
"|1|hashed|entry ssh-ed25519 AAAA",
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
"",
].join("\n"),
);
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
const hosts = yield* sshEnvironment.discoverHosts({ homeDir });
assert.deepEqual(hosts, [
{
alias: "bastion.example.com",
hostname: "bastion.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
source: "ssh-config",
},
{
alias: "known.example.com",
hostname: "known.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "staging",
hostname: "staging",
username: null,
port: null,
source: "ssh-config",
},
]);
}).pipe(
Effect.provide(
DesktopSshEnvironment.layer().pipe(
Layer.provideMerge(
Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {
request: () => Effect.die("unexpected password prompt request"),
resolve: () => Effect.die("unexpected password prompt resolution"),
cancelPending: () => Effect.void,
}),
),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
),
),
Effect.scoped,
),
);
});
@@ -0,0 +1,150 @@
import type {
DesktopDiscoveredSshHost,
DesktopSshEnvironmentBootstrap,
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
type SshPasswordRequest,
} from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import {
SshCommandError,
SshHostDiscoveryError,
SshInvalidTargetError,
SshLaunchError,
SshPairingError,
SshPasswordPromptError,
SshReadinessError,
} from "@t3tools/ssh/errors";
import { SshEnvironmentManager, type RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
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 Path from "effect/Path";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
export type DesktopSshEnvironmentRuntimeServices =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
| NetService.NetService;
export type DesktopSshEnvironmentOperationError =
| SshCommandError
| SshInvalidTargetError
| SshLaunchError
| SshPairingError
| SshReadinessError
| SshPasswordPromptError
| NetService.NetError;
export type DesktopSshEnvironmentDiscoverError = SshHostDiscoveryError;
export type DesktopSshEnvironmentError =
| DesktopSshEnvironmentDiscoverError
| DesktopSshEnvironmentOperationError;
export interface DesktopSshEnvironmentShape {
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
}
export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment,
DesktopSshEnvironmentShape
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
}
function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
return discoverSshHosts(input ?? {});
}
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError {
return (
error instanceof SshPasswordPromptError &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
);
}
const makePasswordPrompt = (
prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPromptsShape,
): SshPasswordPromptShape => ({
isAvailable: true,
request: (request: SshPasswordRequest) =>
prompts.request(request).pipe(
Effect.mapError(
(cause) =>
new SshPasswordPromptError({
message: cause.message,
cause,
}),
),
),
});
const make = Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>();
const passwordPrompt = SshPasswordPrompt.of(makePasswordPrompt(prompts));
return DesktopSshEnvironment.of({
discoverHosts: (input) =>
discoverDesktopSshHostsEffect(input).pipe(
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.discoverHosts"),
),
ensureEnvironment: (target, ensureOptions) =>
manager
.ensureEnvironment(target, ensureOptions)
.pipe(
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.ensureEnvironment"),
),
disconnectEnvironment: (target) =>
manager
.disconnectEnvironment(target)
.pipe(
Effect.provideService(SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
),
});
});
export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide(
SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
...(options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner }),
}),
),
);
@@ -0,0 +1,146 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts";
interface SentMessage {
readonly channel: string;
readonly args: readonly unknown[];
}
function makeTestWindow() {
const listeners = new Map<string, Set<() => void>>();
const sentMessages: SentMessage[] = [];
let destroyed = false;
let minimized = true;
let restored = false;
let focused = false;
const window = {
isDestroyed: () => destroyed,
isMinimized: () => minimized,
restore: () => {
restored = true;
minimized = false;
},
focus: () => {
focused = true;
},
once: (eventName: string, listener: () => void) => {
const eventListeners = listeners.get(eventName) ?? new Set<() => void>();
eventListeners.add(listener);
listeners.set(eventName, eventListeners);
},
removeListener: (eventName: string, listener: () => void) => {
listeners.get(eventName)?.delete(listener);
},
webContents: {
send: (channel: string, ...args: readonly unknown[]) => {
sentMessages.push({ channel, args });
},
},
};
return {
window,
sentMessages,
isRestored: () => restored,
isFocused: () => focused,
close: () => {
destroyed = true;
const closedListeners = [...(listeners.get("closed") ?? [])];
listeners.delete("closed");
for (const listener of closedListeners) {
listener();
}
},
};
}
function makeElectronWindowLayer(window: ReturnType<typeof makeTestWindow>["window"]) {
return Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
create: () => Effect.die("unexpected BrowserWindow creation"),
main: Effect.succeed(Option.some(window as Electron.BrowserWindow)),
currentMainOrFirst: Effect.succeed(Option.some(window as Electron.BrowserWindow)),
focusedMainOrFirst: Effect.succeed(Option.some(window as Electron.BrowserWindow)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: () => Effect.void,
sendAll: () => Effect.void,
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
}),
);
}
function makeLayer(window: ReturnType<typeof makeTestWindow>["window"]) {
return DesktopSshPasswordPrompts.layer({ passwordPromptTimeoutMs: 1_000 }).pipe(
Layer.provide(makeElectronWindowLayer(window)),
Layer.provide(NodeServices.layer),
Layer.provideMerge(TestClock.layer()),
);
}
describe("DesktopSshPasswordPrompts", () => {
it.effect("sends renderer prompts and resolves them by request id", () => {
const testWindow = makeTestWindow();
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const fiber = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
assert.ok(sent);
assert.equal(sent.channel, IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL);
const request = sent.args[0] as { readonly requestId: string; readonly destination: string };
assert.equal(request.destination, "devbox");
assert.equal(testWindow.isRestored(), true);
assert.equal(testWindow.isFocused(), true);
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
assert.equal(yield* Fiber.join(fiber), "secret");
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("times out pending renderer prompts with a typed error", () => {
const testWindow = makeTestWindow();
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const fiber = yield* prompts
.request({
destination: "devbox",
username: null,
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(1_000));
const error = yield* Fiber.join(fiber).pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError);
assert.equal(error.destination, "devbox");
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
});
@@ -0,0 +1,337 @@
import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts";
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
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 * as IpcChannels from "../ipc/channels.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
export class DesktopSshPromptUnavailableError extends Data.TaggedError(
"DesktopSshPromptUnavailableError",
)<{
readonly reason: string;
}> {
override get message() {
return this.reason;
}
}
export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
"DesktopSshPromptWindowUnavailableError",
)<{
readonly destination: string;
}> {
override get message() {
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
readonly requestId: string;
readonly destination: string;
readonly cause: unknown;
}> {
override get message() {
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
export class DesktopSshPromptTimedOutError extends Data.TaggedError(
"DesktopSshPromptTimedOutError",
)<{
readonly requestId: string;
readonly destination: string;
}> {
override get message() {
return `SSH authentication timed out for ${this.destination}.`;
}
}
export class DesktopSshPromptCancelledError extends Data.TaggedError(
"DesktopSshPromptCancelledError",
)<{
readonly requestId: string;
readonly destination: string;
readonly reason: string;
}> {
override get message() {
return this.reason;
}
}
export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
"DesktopSshPromptInvalidRequestIdError",
)<{
readonly requestId: string;
}> {
override get message() {
return "Invalid SSH password prompt id.";
}
}
export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
readonly requestId: string;
}> {
override get message() {
return "SSH password prompt expired. Try connecting again.";
}
}
export type DesktopSshPasswordPromptRequestError =
| DesktopSshPromptUnavailableError
| DesktopSshPromptWindowUnavailableError
| DesktopSshPromptSendError
| DesktopSshPromptTimedOutError
| DesktopSshPromptCancelledError;
export type DesktopSshPasswordPromptResolveError =
| DesktopSshPromptInvalidRequestIdError
| DesktopSshPromptExpiredError;
export type DesktopSshPasswordPromptError =
| DesktopSshPasswordPromptRequestError
| DesktopSshPasswordPromptResolveError;
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
return (
error instanceof DesktopSshPromptCancelledError ||
error instanceof DesktopSshPromptTimedOutError
);
}
export interface DesktopSshPasswordPromptsShape {
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
readonly resolve: (
input: DesktopSshPasswordPromptResolutionInput,
) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
readonly cancelPending: (reason: string) => Effect.Effect<void>;
}
export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts,
DesktopSshPasswordPromptsShape
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
interface PendingSshPasswordPrompt {
readonly requestId: string;
readonly destination: string;
readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
}
interface LayerOptions {
readonly passwordPromptTimeoutMs?: number;
}
const removePending = (
pendingRef: Ref.Ref<Map<string, PendingSshPasswordPrompt>>,
requestId: string,
) =>
Ref.modify(pendingRef, (pending) => {
const entry = pending.get(requestId);
if (entry === undefined) {
return [Option.none<PendingSshPasswordPrompt>(), pending] as const;
}
const nextPending = new Map(pending);
nextPending.delete(requestId);
return [Option.some(entry), nextPending] as const;
});
const failPending = (
pending: PendingSshPasswordPrompt,
error: DesktopSshPasswordPromptRequestError,
) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
const cancelPending = (reason: string): Effect.Effect<void> =>
Ref.getAndSet(pendingRef, new Map()).pipe(
Effect.flatMap((pending) =>
Effect.forEach(
pending.values(),
(entry) =>
failPending(
entry,
new DesktopSshPromptCancelledError({
requestId: entry.requestId,
destination: entry.destination,
reason,
}),
),
{ discard: true },
),
),
Effect.asVoid,
);
yield* Effect.addFinalizer(() =>
cancelPending("SSH password prompt service stopped.").pipe(Effect.ignore),
);
const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
input: DesktopSshPasswordPromptResolutionInput,
): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
const requestId = input.requestId.trim();
if (requestId.length === 0) {
return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
}
const pending = yield* removePending(pendingRef, requestId);
if (Option.isNone(pending)) {
return yield* new DesktopSshPromptExpiredError({ requestId });
}
const entry = pending.value;
if (input.password === null) {
yield* failPending(
entry,
new DesktopSshPromptCancelledError({
requestId,
destination: entry.destination,
reason: `SSH authentication cancelled for ${entry.destination}.`,
}),
);
return;
}
yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
});
const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
input: SshPasswordRequest,
): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
const window = yield* electronWindow.main;
if (Option.isNone(window) || window.value.isDestroyed()) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
);
const promptRequest: DesktopSshPasswordPromptRequest = {
requestId,
destination: input.destination,
username: input.username,
prompt: input.prompt,
expiresAt,
};
const deferred = yield* Deferred.make<string, DesktopSshPasswordPromptRequestError>();
const pending: PendingSshPasswordPrompt = {
requestId,
destination: input.destination,
deferred,
};
yield* Ref.update(pendingRef, (entries) => new Map(entries).set(requestId, pending));
const context = yield* Effect.context();
const runFork = Effect.runForkWith(context);
const cancelOnWindowClosed = () => {
runFork(
removePending(pendingRef, requestId).pipe(
Effect.flatMap((entry) =>
Option.match(entry, {
onNone: () => Effect.void,
onSome: (pending) =>
failPending(
pending,
new DesktopSshPromptCancelledError({
requestId,
destination: input.destination,
reason: "SSH authentication was cancelled because the app window closed.",
}),
),
}),
),
),
);
};
const cleanup = Effect.sync(() => {
if (!window.value.isDestroyed()) {
window.value.removeListener("closed", cancelOnWindowClosed);
}
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
const waitForPassword = Deferred.await(deferred).pipe(
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new DesktopSshPromptTimedOutError({
requestId,
destination: input.destination,
}),
),
onSome: Effect.succeed,
}),
),
);
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
}
window.value.focus();
},
catch: (cause) =>
new DesktopSshPromptSendError({
requestId,
destination: input.destination,
cause,
}),
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
});
return DesktopSshPasswordPrompts.of({
request,
resolve,
cancelPending,
});
});
export const layer = (options: LayerOptions = {}) =>
Layer.effect(DesktopSshPasswordPrompts, make(options));
@@ -0,0 +1,79 @@
import { assert, describe, it } from "@effect/vitest";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as DesktopSshRemoteApi from "./DesktopSshRemoteApi.ts";
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
request,
new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
}),
);
}
function makeLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
) {
return DesktopSshRemoteApi.layer.pipe(
Layer.provide(
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
),
),
);
}
describe("DesktopSshRemoteApi", () => {
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
const layer = makeLayer((request) =>
Effect.sync(() => {
requestUrls.push(request.url);
return jsonResponse(request, {
environmentId: "remote-env",
label: "Remote Devbox",
platform: { os: "linux", arch: "x64" },
serverVersion: "1.2.3",
capabilities: { repositoryIdentity: true },
});
}),
);
return Effect.gen(function* () {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
const descriptor = yield* remoteApi.fetchEnvironmentDescriptor({
httpBaseUrl: "http://127.0.0.1:41773/",
});
assert.equal(descriptor.label, "Remote Devbox");
assert.deepEqual(requestUrls, ["http://127.0.0.1:41773/.well-known/t3/environment"]);
}).pipe(Effect.provide(layer));
});
it.effect("wraps schema decode failures in a typed remote api error", () => {
const layer = makeLayer((request) =>
Effect.succeed(jsonResponse(request, { environmentId: "remote-env" })),
);
return Effect.gen(function* () {
const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;
const error = yield* remoteApi
.fetchEnvironmentDescriptor({
httpBaseUrl: "http://127.0.0.1:41773/",
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshRemoteApi.DesktopSshRemoteApiError);
assert.equal(error.operation, "fetch-environment-descriptor");
assert.equal(error.cause instanceof SshHttpBridgeError, false);
}).pipe(Effect.provide(layer));
});
});
+124
View File
@@ -0,0 +1,124 @@
import {
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
type AuthBearerBootstrapResult as AuthBearerBootstrapResultType,
type AuthSessionState as AuthSessionStateType,
type AuthWebSocketTokenResult as AuthWebSocketTokenResultType,
ExecutionEnvironmentDescriptor,
type ExecutionEnvironmentDescriptor as ExecutionEnvironmentDescriptorType,
} from "@t3tools/contracts";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import { fetchLoopbackSshJson } from "@t3tools/ssh/tunnel";
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 Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
export type DesktopSshRemoteApiOperation =
| "fetch-environment-descriptor"
| "bootstrap-bearer-session"
| "fetch-session-state"
| "issue-websocket-token";
export class DesktopSshRemoteApiError extends Data.TaggedError("DesktopSshRemoteApiError")<{
readonly operation: DesktopSshRemoteApiOperation;
readonly cause: SshHttpBridgeError | Schema.SchemaError;
}> {
override get message() {
return `SSH remote API request failed during ${this.operation}.`;
}
}
export interface DesktopSshRemoteApiShape {
readonly fetchEnvironmentDescriptor: (input: {
readonly httpBaseUrl: string;
}) => Effect.Effect<ExecutionEnvironmentDescriptorType, DesktopSshRemoteApiError>;
readonly bootstrapBearerSession: (input: {
readonly httpBaseUrl: string;
readonly credential: string;
}) => Effect.Effect<AuthBearerBootstrapResultType, DesktopSshRemoteApiError>;
readonly fetchSessionState: (input: {
readonly httpBaseUrl: string;
readonly bearerToken: string;
}) => Effect.Effect<AuthSessionStateType, DesktopSshRemoteApiError>;
readonly issueWebSocketToken: (input: {
readonly httpBaseUrl: string;
readonly bearerToken: string;
}) => Effect.Effect<AuthWebSocketTokenResultType, DesktopSshRemoteApiError>;
}
export class DesktopSshRemoteApi extends Context.Service<
DesktopSshRemoteApi,
DesktopSshRemoteApiShape
>()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}
const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(
ExecutionEnvironmentDescriptor,
);
const decodeAuthBearerBootstrapResult = Schema.decodeUnknownEffect(AuthBearerBootstrapResult);
const decodeAuthSessionState = Schema.decodeUnknownEffect(AuthSessionState);
const decodeAuthWebSocketTokenResult = Schema.decodeUnknownEffect(AuthWebSocketTokenResult);
const mapError =
(operation: DesktopSshRemoteApiOperation) =>
(cause: SshHttpBridgeError | Schema.SchemaError): DesktopSshRemoteApiError =>
new DesktopSshRemoteApiError({ operation, cause });
const make = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const provideHttpClient = <A, E>(effect: Effect.Effect<A, E, HttpClient.HttpClient>) =>
effect.pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
return DesktopSshRemoteApi.of({
fetchEnvironmentDescriptor: ({ httpBaseUrl }) =>
fetchLoopbackSshJson<unknown>({
httpBaseUrl,
pathname: "/.well-known/t3/environment",
}).pipe(
Effect.flatMap(decodeExecutionEnvironmentDescriptor),
Effect.mapError(mapError("fetch-environment-descriptor")),
provideHttpClient,
Effect.withSpan("desktop.sshRemoteApi.fetchEnvironmentDescriptor"),
),
bootstrapBearerSession: ({ httpBaseUrl, credential }) =>
fetchLoopbackSshJson<unknown>({
httpBaseUrl,
pathname: "/api/auth/bootstrap/bearer",
method: "POST",
body: { credential },
}).pipe(
Effect.flatMap(decodeAuthBearerBootstrapResult),
Effect.mapError(mapError("bootstrap-bearer-session")),
provideHttpClient,
Effect.withSpan("desktop.sshRemoteApi.bootstrapBearerSession"),
),
fetchSessionState: ({ httpBaseUrl, bearerToken }) =>
fetchLoopbackSshJson<unknown>({
httpBaseUrl,
pathname: "/api/auth/session",
bearerToken,
}).pipe(
Effect.flatMap(decodeAuthSessionState),
Effect.mapError(mapError("fetch-session-state")),
provideHttpClient,
Effect.withSpan("desktop.sshRemoteApi.fetchSessionState"),
),
issueWebSocketToken: ({ httpBaseUrl, bearerToken }) =>
fetchLoopbackSshJson<unknown>({
httpBaseUrl,
pathname: "/api/auth/ws-token",
method: "POST",
bearerToken,
}).pipe(
Effect.flatMap(decodeAuthWebSocketTokenResult),
Effect.mapError(mapError("issue-websocket-token")),
provideHttpClient,
Effect.withSpan("desktop.sshRemoteApi.issueWebSocketToken"),
),
});
});
export const layer = Layer.effect(DesktopSshRemoteApi, make);
@@ -1,85 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("does nothing outside macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
-29
View File
@@ -1,29 +0,0 @@
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
if ((options.platform ?? process.platform) !== "darwin") return;
try {
const shell = env.SHELL ?? "/bin/zsh";
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
-145
View File
@@ -1,145 +0,0 @@
import { describe, expect, it } from "vitest";
import type { DesktopUpdateState } from "@t3tools/contracts";
import {
getCanRetryAfterDownloadFailure,
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
describe("shouldBroadcastDownloadProgress", () => {
it("broadcasts the first downloading progress update", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: null },
1,
),
).toBe(true);
});
it("skips progress updates within the same 10% bucket", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
18.7,
),
).toBe(false);
});
it("broadcasts progress updates when a new 10% bucket is reached", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
20.1,
),
).toBe(true);
});
it("broadcasts progress updates when a retry resets the download percentage", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
0.2,
),
).toBe(true);
});
});
describe("getAutoUpdateDisabledReason", () => {
it("reports development builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: true,
isPackaged: false,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("packaged production builds");
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
it("reports linux non-AppImage builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "linux",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("AppImage");
});
});
describe("nextStatusAfterDownloadFailure", () => {
it("returns available when an update version is still known", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe("available");
});
it("returns error when no update version can be retried", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe("error");
});
});
describe("getCanRetryAfterDownloadFailure", () => {
it("returns true when an available version is still present", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe(true);
});
it("returns false when no version is available to retry", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe(false);
});
});
-48
View File
@@ -1,48 +0,0 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
export function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
): boolean {
if (currentState.status !== "downloading") {
return true;
}
const currentPercent = currentState.downloadPercent;
if (currentPercent === null) {
return true;
}
const previousStep = Math.floor(currentPercent / 10);
const nextStep = Math.floor(nextPercent / 10);
return nextStep !== previousStep || nextPercent === 100;
}
export function nextStatusAfterDownloadFailure(
currentState: DesktopUpdateState,
): DesktopUpdateState["status"] {
return currentState.availableVersion ? "available" : "error";
}
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
return currentState.availableVersion !== null;
}
export function getAutoUpdateDisabledReason(args: {
isDevelopment: boolean;
isPackaged: boolean;
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
}): string | null {
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
if (args.disabledByEnv) {
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
}
if (args.platform === "linux" && !args.appImage) {
return "Automatic updates on Linux require running the AppImage build.";
}
return null;
}
Loaded 100 of 1415 files, more files were not shown because too many files have changed in this diff. Show more