Compare commits

..
Author SHA1 Message Date
Theo Browne 929d35a1e8 Merge main into t3code/disable-pairing-codes 2026-07-22 04:10:27 -07:00
32c6012dab Sidebar v2 beta: flat thread list with a server-backed settled lifecycle (#4026)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
2026-07-22 03:36:34 -07:00
Theo BrowneandClaude Fable 5 6f34ad3e87 fix(claude): handle all SDK stream messages; stop spurious work-log warning rows (#4244)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 19:58:39 -07:00
Theo BrowneandClaude Fable 5 62cf461759 fix: better defaults — Claude 1M context, Codex gpt-5.6, worktrees from origin main (#4240)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 17:13:44 -07:00
Theo BrowneandClaude Fable 5 23c18fda7a fix(web): keep composer editable while disconnected (#4241)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 14:29:23 -07:00
Theo BrowneandClaude Fable 5 c0bb237345 fix(web): always show environment chip for remote projects (#4217)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 18:27:57 -07:00
Julius Marmingeandcodex 5d34f9ff23 Pass CLI OAuth config to hosted web deploy (#4186)
Co-authored-by: codex <[email protected]>
2026-07-20 14:22:35 +00:00
ssandJulius Marminge c8a04bd59b Finale: upgrade changed files card to fix various UI issues (#4113)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 12:45:36 +00:00
db4b2d8a0f perf(orchestration): speed up new-chat propagation and offline catch-up (#4177)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 14:44:58 +02:00
2c199aacac fix(desktop): preserve main window bounds (#3851)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-20 14:43:22 +02:00
Yordis PrietoandJulius Marminge 8ca4eec9ca feat(web): drag files from the explorer into the chat composer (#4140)
Co-authored-by: Julius Marminge <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-20 14:26:46 +02:00
0936fd271f fix(web): preview workspace images in the file panel (#3996)
Co-authored-by: Rhiz3K <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 14:22:03 +02:00
Maxwell Young fa69f05b69 [codex] preserve custom model slugs (#4168) 2026-07-20 13:32:30 +02:00
Yordis Prieto c710167bde fix(web): paint text selection over composer chips (#4139)
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-20 13:30:16 +02:00
Maxwell Young a135f2c2d3 [codex] show complete approval details (#4111) 2026-07-20 13:16:57 +02:00
xxashxx-svgandClaude Fable 5 946b867666 fix(web): scope timeline minimap hover target to the side gutter (#3869)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 11:16:47 +00:00
Utkarsh Patil 0ca3240691 fix(server): use CLI for OpenCode health check instead of spawning server (#4153) 2026-07-20 12:22:00 +02:00
Vadym Kotaiandcodex f4da4f3b40 fix(opencode): resume the OpenCode session on follow-ups instead of starting an empty one (#3617)
Co-authored-by: codex <[email protected]>
2026-07-20 10:20:28 +00:00
Julius Marmingeandcodex b6d9ce325c Gate iOS glass layout on native support (#4032)
Co-authored-by: codex <[email protected]>
2026-07-20 10:17:30 +00:00
Julius Marmingeandcodex 8e3467fe60 Synchronize mobile threads with authoritative shell snapshots (#4163)
Co-authored-by: codex <[email protected]>
2026-07-20 11:54:59 +02:00
2fae0d0ac3 fix(preview): preserve direct localhost navigation (#3939)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-20 11:49:22 +02:00
Julius Marmingeandcodex 08993a5ec8 Regenerate Codex reset credit protocol bindings (#4173)
Co-authored-by: codex <[email protected]>
2026-07-20 11:14:19 +02:00
Andrew ForsterandJulius Marminge 501ce27b81 [orchestration] Clear stale active turn when session becomes inactive (#3159)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 11:04:48 +02:00
40c0ab0883 Add Codex launch arguments setting (#2892)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: root <[email protected]>
2026-07-20 11:04:03 +02:00
Guilherme VieiraandJulius Marminge 33f1cb4224 fix(codex): show web search query and url in tool call details (#2093)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 10:58:38 +02:00
d266c068d0 fix: allow sidebar to be shrunk when wider than viewport (#2456)
Co-authored-by: Shoaib Ansari <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-20 10:58:20 +02:00
Andrew Barnes 5fcfe242c1 fix(cli): support force removing projects (#3922) 2026-07-20 08:53:02 +00:00
Christoph Herzog df65a6c3ad Archive selected threads from the context menu (#3895) 2026-07-20 08:51:22 +00:00
Tristan Knight 3235658c08 fix: delegate OpenCode session titles to provider (#3720) 2026-07-20 08:43:07 +00:00
Theo BrowneandClaude Fable 5 749baec353 feat(server): title background-task work-log rows with the task name (#3751)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 10:42:02 +02:00
mel d7baa37e5c Fix incorrect pluralization of “entry” (#3933) 2026-07-20 08:35:47 +00:00
Pieter van Zyl 68ea280388 fix(server): recognize Bedrock-backed Claude as authenticated (#3931) 2026-07-20 08:35:08 +00:00
Andrew Barnes dfbda84362 fix(web): handle sidebar shortcut before editors (#3921) 2026-07-20 08:33:43 +00:00
Carlos Rico-Ospina 78485e6d50 fix(desktop): allow clipboard writes in the preview browser (#3889) 2026-07-20 08:32:44 +00:00
coach007 63b6b44627 Fix project action preview settings persistence (#3842) 2026-07-20 08:32:14 +00:00
David Whatley 3795dbb017 fix(server): resolve Claude SDK executable path on Windows npm installs (#3740) 2026-07-20 08:31:13 +00:00
eeinarsson 2640e6dcfc fix(client): use lightweight connection probe (#4137) 2026-07-20 01:33:01 +02:00
Julius Marmingeandcodex e34250df46 Add portable mobile app testing guidance (#4165)
Co-authored-by: codex <[email protected]>
2026-07-20 01:32:19 +02:00
Julius Marmingeandcodex 7e1a0d551c Fix draft banner stack overlap (#4164)
Co-authored-by: codex <[email protected]>
2026-07-20 01:24:57 +02:00
maria b511227b7a fix(web): improve dev sidebar backdrop contrast & remove version pills (#4166) 2026-07-19 21:02:23 +00:00
Julius MarmingeandClaude Sonnet 5 69c8be2ee5 Make test-t3-app skill discoverable by Claude Code (#4162)
Co-authored-by: Claude Sonnet 5 <[email protected]>
2026-07-19 20:32:36 +02:00
Julius Marmingeandcodex 271454cbd2 fix(mobile): Stabilize native stack option updates (#4037)
Co-authored-by: codex <[email protected]>
2026-07-19 19:40:22 +02:00
Kriday Dave e8ff6bc7f8 fix(shared): delete unused agentAwareness phase predicates (#4134) 2026-07-19 19:37:22 +02:00
Utkarsh Patil 398140a9bd fix: increase OpenCode server startup timeout from 5s to 30s (#4132) 2026-07-19 19:33:10 +02:00
Julius Marmingeandcodex 2b180a2b2d Refine T3 Connect authorization surfaces (#4159)
Co-authored-by: codex <[email protected]>
2026-07-19 19:23:53 +02:00
7a820abfdd feat: add headless t3 connect setup for SSH hosts (#3749)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-19 18:59:23 +02:00
53e3c98a55 feat(web): themed sidebar header art for nightly and dev builds (#4130)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 12:35:58 +02:00
Julius Marmingeandcodex 4f11740510 Add isolated app testing workflow (#4121)
Co-authored-by: codex <[email protected]>
2026-07-19 11:57:58 +02:00
Taras 1735e27d9e Add terminal selection copy action (#2904) 2026-07-19 00:05:09 +02:00
Julius Marminge ebe8afb1df Refresh splash screen and favicon branding (#4120) 2026-07-18 15:44:06 +02:00
Utkarsh PatilandJulius Marminge bf76535fe4 fix(desktop): Validate WSL node version against engine range after probe success (#3621)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 11:54:13 +00:00
5c66110e26 [fix/feat:ui] Make selected menu checks blue (#3234)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-18 13:50:33 +02:00
Maxwell Young da3c2030f7 [codex] canonicalize client timestamps (#4112) 2026-07-18 13:40:34 +02:00
Noah ZepnerandJulius Marminge 0506508e9b Allow failed remote environments to be removed (#4084)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:31:10 +02:00
Guilherme VieiraandJulius Marminge b859a575d1 fix(web): handle macOS Home and End in composer (#2508)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:23:57 +02:00
ssandJulius Marminge e63403fe92 [fix/feat:ui] Preserve open-in editor brand colors (#3225)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:22:37 +02:00
ssandJulius Marminge c0e161af06 [fix/feat:ui] Show default option badge (#3232)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:21:50 +02:00
d0b9f8d40d [codex] Route OpenCode missing-session errors through Effect (#3608)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:52 +02:00
Jake LeventhalandJulius Marminge d8b12ae801 Fix sending messages during active turns (#3919)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:14 +02:00
Jake LeventhalandJulius Marminge 31caa5652b Fix reopening existing Diff tab (#3973)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:18:18 +02:00
Aditya Mer e350c0a07b Add Grok to marketing site provider list (#3484) 2026-07-18 11:18:17 +00:00
Jake LeventhalandJulius Marminge 38e0bb07bb Default diffs to working changes (#3974)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:17:30 +02:00
Chris Michael Guzman 765e1b5fc0 perf(client): defer active thread cache writes (#4006) 2026-07-18 13:16:38 +02:00
AlexandJulius Marminge 03e20c875c fix(mobile): restore iOS home screen branding (#4025)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:14:59 +02:00
Julius Marmingeandcodex 2318e00270 fix(web): avoid duplicate mention text on paste
Co-authored-by: codex <[email protected]>
2026-07-18 13:05:45 +02:00
Yordis PrietoandJulius Marminge 4cfec8c128 feat: file explorer mention actions and zoom-aware context menus (#4054)
Signed-off-by: Yordis Prieto <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:05:26 +02:00
1bd2fa25e2 feat: draft hero landing on the index route (#4055)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-18 12:45:45 +02:00
5ca32661b7 fix(web): increase contrast of question option descriptions (#3867)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:53:50 +02:00
Julius Marminge 8b33799523 Preserve T3 Code identity in macOS development launcher (#4102) 2026-07-17 23:39:29 +02:00
Julius Marminge 24f9c2a08e Share MCP OAuth locks across Codex shadow homes (#4104) 2026-07-17 23:26:53 +02:00
31ca9e5531 fix(server): skip undecodable provider runtime rows when listing sessions (#3951)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 21:26:22 +00:00
73bf127d71 [codex] Fix provider update checks restore defaults (#3531)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:25:21 +02:00
43e2aeab38 [codex] fix: tolerate invalid latest user message timestamps (#3521)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:52 +02:00
b655a9f183 [codex] fix: guard invalid web timestamps (#3515)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:10 +02:00
Matt Van HornandJulius Marminge 4e3f2f04d5 fix(server): thread cwd through Claude capability probe (#2048) (#2124)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:22:19 +02:00
1047dac0c5 fix(terminal): strip AppImage runtime env from spawned terminals (#3108)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:21:19 +02:00
JamesandJulius Marminge 143b9c9280 fix(ux): spamming cmd + , no longer stack opening settings (#2757)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:20:28 +02:00
cf58cadd02 feat(server): include runtime model and effort in Codex developer instructions (#3948)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:15:53 +02:00
6a17629670 [codex] fix mobile composer Enter behavior (#3930)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:14:45 +02:00
7b8d12618b fix(web): inset Windows desktop scrollbars from resize edge (#4097)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:52:42 +00:00
Maxwell YoungandJulius Marminge bcd640bf4d [codex] prevent ACP assistant ID collisions after restarts (#3932)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:51:16 +02:00
b49a2e677c Remove unused code parameter from describePreviewError (#3970)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:50:33 +00:00
ed81c156da fix(server): image upload crashed dispatchCommand with a stack overflow (#3952)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:52 +02:00
Kriday DaveandJulius Marminge 7dc75127c2 Fix duplicate keybinding rule when replacing with an existing rule (#3969)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:35 +02:00
Fazal Kadivar e057e2e985 fix: prevent initial right-click from selecting a context menu item (#3877) 2026-07-17 21:42:13 +02:00
Olivier Melcher a7f6d97b94 Allow preview panel to grow on wide displays (#4044) 2026-07-17 18:40:24 +00:00
Kriday DaveandJulius Marminge f9a4f59930 Fix documented task-runner commands (bun run -> vp) (#3965)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 20:35:24 +02:00
BunnyGamezsc 7f1cb61031 fix(cursor): default binary path to cursor-agent (avoid path conflict w/ grok) (#4094) 2026-07-17 18:01:02 +00:00
Kriday Dave c49d424e3a Normalize protocol-relative remote host input as https (#3971) 2026-07-17 18:59:42 +02:00
Manuel De Ceglie 4804a9824f fix(marketing): correct Cursor icon color (#4090) 2026-07-17 18:56:59 +02:00
Manuel De Ceglie 0748134cec Update marketing GitHub star count (#4088) 2026-07-17 18:56:35 +02:00
Julius Marmingeandcodex 6e9987cf17 Refresh app icons across release variants (#4080)
Co-authored-by: codex <[email protected]>
2026-07-17 18:51:14 +02:00
Eric Tsai 8b5469863a fix(server): stabilize non-repository Git diagnostics (#4077) 2026-07-17 11:15:31 +00:00
Eric Tsai 58302b2010 fix(git): treat selected commit paths literally (#3998) 2026-07-17 11:14:29 +00:00
Hugo Vizcaino SantanaandClaude Opus 4.8 1f2797325b feat: show nightly update changelog tooltip (#3832)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-17 13:10:51 +02:00
Ishan c14a5ca492 Fix dropped events during initial thread snapshot (#4079) 2026-07-17 11:58:09 +02:00
Dimitar StoykovandClaude Opus 4.8 eb733c10f2 fix(server): use CLAUDE_CONFIG_DIR instead of HOME for Claude instanc… (#4017)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-17 11:46:55 +02:00
Julius Marmingeandcodex 8a02c71861 [codex] Expand real-route app store screenshot harness (#4014)
Co-authored-by: codex <[email protected]>
2026-07-17 11:33:40 +02:00
Julius Marmingeandcodex fdca15471d Add native mobile share target support (#4021)
Co-authored-by: codex <[email protected]>
2026-07-16 14:29:17 +00:00
Julius Marminge 5d68fca8f2 Fix iOS terminal Enter input encoding (#4043) 2026-07-16 16:17:03 +02:00
Julius Marminge 2a33a18716 fix(mobile): Send composer images in upload wire format (#4035) 2026-07-16 13:04:41 +02:00
Julius Marmingeandcodex bde0a4c0dd Resolve localhost preview URLs for remote environments (#4011)
Co-authored-by: codex <[email protected]>
2026-07-16 11:07:38 +02:00
Julius Marmingeandcodex 54f167e2e0 Normalize over-indented markdown list items (#4020)
Co-authored-by: codex <[email protected]>
2026-07-16 08:47:36 +00:00
Julius Marmingeandcodex d114e2772d Prevent duplicate project workspace roots (#3829)
Co-authored-by: codex <[email protected]>
2026-07-16 10:39:13 +02:00
Ishan 0418301de7 Fix macOS fullscreen titlebar spacing (#4019) 2026-07-16 09:34:33 +02:00
Julius Marminge 5e8b2c800e Isolate native diff highlight grammar state (#4029) 2026-07-16 09:24:41 +02:00
Julius Marmingeandcodex b98233702c [codex] Fix onboarding connection status (#4001)
Co-authored-by: codex <[email protected]>
2026-07-16 09:22:07 +02:00
Julius Marmingeandcodex ecb35f7583 Fix Legal modal header crash (#4000)
Co-authored-by: codex <[email protected]>
2026-07-15 10:48:55 +00:00
Julius Marmingeandcodex d359789ed4 docs: Add T3 Code Legal Docs (#3972)
Co-authored-by: codex <[email protected]>
2026-07-15 11:44:03 +02:00
Kriday Dave 462442667e fix(docs): replace stale codething-mvp absolute paths with repo-relative links (#3992) 2026-07-15 10:55:01 +02:00
Kriday Dave c69120f484 fix(docs): repair broken source links in architecture overview (#3991) 2026-07-15 10:54:40 +02:00
Kriday Dave 7b928d5488 fix(docs): correct CI task-runner commands in ci.md (#3990) 2026-07-15 10:53:48 +02:00
Theo Browne 2fdc704bbb perf(web): duty-cycle status animations and remove fixed noise overlay (#3978) 2026-07-15 09:08:33 +02:00
Julius Marminge 3513fa04fb Prepare Android beta branding and review diff UI (#3967) 2026-07-14 19:21:12 +02:00
Julius Marminge 735240f316 Skip stale working-task notifications (#3961) 2026-07-14 18:00:16 +02:00
Julius Marminge 8de254a685 Use client-side fallbacks for missing project favicons (#3959) 2026-07-14 17:59:00 +02:00
Theo BrowneandClaude Fable 5 9faf5533eb fix: restrict 127.* loopback matching to real IPv4 addresses
A prefix test also accepted DNS names like 127.attacker.example, which
would pass both the devUrl eligibility check and the Host header guard
(review finding from macroscope).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-13 18:19:48 -07:00
Theo BrowneandClaude Fable 5 03a9e682f1 feat: silent pairing for local web-dev servers
Local web dev previously required scraping a one-time, 5-minute
/pair#token URL from dev-runner stdout for every fresh browser context,
which made parallel-instance work and agent browser verification
painful. The web app now authenticates automatically against eligible
dev servers via a guarded dev-only endpoint.

Server: POST /api/auth/dev-pairing-token mints a one-time administrative
credential (subject dev-auto-bootstrap, hidden from pairing-link
listings) only when the server is web-mode, loopback-bound
(loopback-browser policy), and configured with a loopback dev URL.
Requests must carry an Origin exactly matching the dev origin (survives
the Vite proxy, unlike Host) and a loopback Host header (DNS-rebinding
defense). Ineligible configs answer an explicit 404 — the handler is
always mounted so the SPA/redirect wildcard can't shadow it.

Startup: eligible dev servers now open the plain dev URL instead of
minting a startup pairing credential the silent path would leave
unconsumed in the URL and scrollback.

Web: the auth-gate bootstrap silently tries the endpoint when
unauthenticated in dev (never in hosted/desktop contexts, never when an
explicit #token is present) and falls back to the pairing screen on any
failure. import.meta.env.DEV keeps the request out of prod bundles.

Extracted host parsing into netHost.ts (auth/http.ts importing the old
helper from http.ts would have been a module cycle; the old helper also
mishandled Host headers with ports).

Docs: AGENTS.md browser-verification section, dev-instance auth notes in
scripts.md (plus stale T3CODE_STATE_DIR fix), and a security spec in
environment-auth.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-13 18:12:16 -07:00
c1ec1915fc [codex] Add Android mobile support (#3579)
Co-authored-by: Horus Lugo <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Shivam Sharma <[email protected]>
Co-authored-by: Ben Davis <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-12 12:03:35 +02:00
Vedank Purohit 619b0ece94 fix(marketing): show platform-appropriate commit shortcut on the website (#3644) 2026-07-12 09:58:55 +00:00
Jake Leventhal ef943a26ab Fix truncated chat error alert layout (#3899) 2026-07-12 09:50:15 +00:00
Julius Marmingeandcodex f61fa9499d Expose mobile PR indicator labels to accessibility (#3828)
Co-authored-by: codex <[email protected]>
2026-07-09 14:00:51 +00:00
Julius Marmingeandcodex 8619ef22e9 Show compact PR number badges in mobile thread rows (#3827)
Co-authored-by: codex <[email protected]>
2026-07-09 15:29:55 +02:00
Julius Marmingeandcodex 843cf176ea fix(mobile): embed fonts and render project favicons reliably (#3823)
Co-authored-by: codex <[email protected]>
2026-07-09 13:49:16 +02:00
Julius Marmingeandcodex ca1e08b5a0 [codex] Label max and ultra reasoning (#3824)
Co-authored-by: codex <[email protected]>
2026-07-09 10:20:32 +00:00
2250e3ee7a feat(client): persist offline environment data and mobile preferences (#3795)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-09 11:23:51 +02:00
Julius Marmingeandcodex 3201e00ad4 [codex] Preserve worktree metadata during branch sync (#3822)
Co-authored-by: codex <[email protected]>
2026-07-09 09:01:23 +02:00
Julius Marmingeandcodex e9127658a6 [codex] Upgrade Clerk stack (#3821)
Co-authored-by: codex <[email protected]>
2026-07-09 07:54:28 +02:00
Patricio Gómez Meneses 18a41388eb Fix desktop native optional dependency packaging (#3816) 2026-07-09 03:55:33 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
Julius MarmingeandCursor Agent 03ac1f0cd9 fix(release): stage pnpm 11 allowBuilds for desktop installs (#3781)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 15:55:18 -07:00
Julius MarmingeandCursor Agent 7778a1cea7 Use rounded depth logo for production splash screen (#3780)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 22:49:50 +00:00
Julius MarmingeandClaude Fable 5 dad0889766 Revert "Revert "Add T3 Connect onboarding for mobile and web"" (#3777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 14:17:18 -07:00
b9cc8d6ef1 Set up Cursor Cloud dev environment (web + Android toolchain) (#3755)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-07 13:18:58 -07:00
Julius MarmingeandClaude Fable 5 0e0040832c Expose Clerk Google sign-in env vars to Expo (#3772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 12:45:40 -07:00
Julius Marminge cd8b9fc8b3 Revert "Add T3 Connect onboarding for mobile and web" (#3776) 2026-07-07 12:40:12 -07:00
Julius Marminge fa6073e2e1 Add T3 Connect onboarding for mobile and web (#3765) 2026-07-07 12:39:56 -07:00
Julius Marminge 4eb1b57933 Lead with the outcome when no agents are active in the Live Activity (#3768) 2026-07-07 09:12:52 -07:00
Julius Marminge 4414f922fe Clear VCS presentation state on finish (#3764) 2026-07-07 08:54:27 -07:00
Julius Marminge 6e42231cb1 Extend Done display to 15 minutes and show up to 5 Live Activity banner rows (#3761) 2026-07-07 02:00:36 -07:00
Julius Marminge bdf5aed665 Fix Expo widget asset wiring order (#3763) 2026-07-07 02:00:10 -07:00
Julius Marminge 0b62e2eb11 Use variant-specific splash icons in mobile app (#3762) 2026-07-07 01:59:13 -07:00
Julius Marminge f9727d0853 Prevent Add Project sheet from collapsing on relayout (#3759) 2026-07-07 01:58:29 -07:00
Julius MarmingeandClaude Opus 4.8 d8e0ba3ea0 Improve live activity routing and diagnostics (#3685)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-07 00:56:20 -07:00
Julius MarmingeandClaude Fable 5 32e7844837 Fix mobile legend anchor under automatic iOS insets (#3684)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-05 22:50:33 -07:00
Julius MarmingeandClaude Opus 4.8 482d56233d Load thread snapshots over HTTP before live sync (#3719)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-05 22:00:13 -07:00
Theo BrowneandClaude Fable 5 6009720844 Add repo-root favicon.svg so t3 code shows its own icon (#3683)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-04 15:05:45 -07:00
Theo BrowneandClaude Opus 4.8 e26e55f389 fix(mobile): combined test branch — scroll, back-swipe, thread lists, computer switching (#3687)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-04 14:28:51 -07:00
Julius Marminge 4ac094fef6 Surface pending tasks in mobile home and draft flow (#3670) 2026-07-03 13:32:14 -07:00
Julius Marminge a7e43b2281 Upgrade Vite Plus and enable bundled dev opt-in (#3679) 2026-07-03 11:21:47 -07:00
Julius MarmingeandClaude Fable 5 cabc93bad3 Make the thread composer read as elevated liquid glass (#3668)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 07:05:38 +00:00
Julius MarmingeandClaude Fable 5 5cda815626 fix(mobile): compile patched native pods from source on EAS (#3667)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-03 06:52:01 +00:00
32d17d3db5 Add adaptive split-view layout for iPad/mobile workspace (#3514)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-02 22:42:14 -07:00
Theo Browne 6d35a87c5d fix(dev): Fix electron dev launch and add test (#3662) 2026-07-02 18:57:59 -07:00
Julius Marminge 7b9eef7ac2 Restore the ultrathink frame border effect (#3625) 2026-07-01 00:25:36 +00:00
Julius Marminge 9d66b104fe Add Claude Sonnet 5 as the default Claude model (#3620) 2026-06-30 11:40:35 -07:00
Utkarsh Patil 51ea084c87 fix: warm WSL before preflight in WSL-only backend mode (#3588) 2026-06-30 11:27:34 -07:00
Hugo BlomandJulius Marminge 0615fd7df1 Add middle-click close for right panel tabs (#3161)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-30 17:13:38 +00:00
t3-code[bot] 2448212367 chore(release): prepare v0.0.28 2026-06-29 22:57:48 +00:00
Julius Marminge fda6486233 Restore chat scroll affordances and add timeline minimap (#3587) 2026-06-29 19:35:16 +00:00
Jgratton24 a9b1190a11 Desktop: parallel WSL + Windows backends with mode picker (#2751) 2026-06-27 08:53:34 -07:00
Julius Marminge 44fb34ad53 Stabilize preview browser surfaces, automation, and recording (#3565) 2026-06-27 08:18:28 -07:00
Julius Marminge 6245c547c2 Fix native composer lag with revision-gated updates (#3574) 2026-06-26 16:55:44 -07:00
Julius Marminge 24abab789e Stabilize chat scroll anchoring after send (#3564) 2026-06-26 14:26:36 -07:00
52b04b947e fix(grok): Harden ACP resume with replay-idle load readiness (#3156)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-25 23:34:08 -07:00
Julius Marmingeandcodex e9ed70c5b9 [codex] Fix preview automation edge cases (#3561)
Co-authored-by: codex <[email protected]>
2026-06-25 20:08:27 -07:00
Julius Marmingeandcodex ffae5410e8 Route preview automation through live owner streams (#3548)
Co-authored-by: codex <[email protected]>
2026-06-25 19:06:44 -07:00
Julius MarmingeandJulius Marminge 31dfe3596e Fix Electron dev and packaged renderer startup (#3557)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-25 20:58:38 +00:00
Julius Marminge c2776c2336 Restore right panel inset when maximized (#3555) 2026-06-25 17:07:33 +00:00
Julius MarmingeandJulius Marminge 22f021ed69 [codex] Upgrade Legend List chat scrolling (#3545)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 15:39:17 -07:00
Wout StiensandCodex a4964b3b36 [codex] fix: show standalone element-pick context (#3527)
Co-authored-by: Codex <[email protected]>
2026-06-23 13:04:20 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
Illia Panasenko 28107e89c2 chore: remove AnnotatableFileDiff leftovers, rename file (#3488) 2026-06-21 20:31:26 -07:00
Julius Marminge 82a9bcc7f4 [codex] add session context to credential errors (#3349) 2026-06-20 20:45:17 -07:00
Julius Marminge 61f8d46fa2 [codex] Enforce Effect error handling conventions (#3380) 2026-06-20 20:43:41 -07:00
Julius Marminge 0debebafbb [codex] Structure thread archive blocked error (#3451) 2026-06-20 20:41:58 -07:00
Julius Marmingeandcodex 2a29de7502 [codex] Structure primary auth validation failures (#3471)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:12 -07:00
Julius Marmingeandcodex 8c1605b383 [codex] Structure OpenCode text generation failures (#3472)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:09 -07:00
Julius Marmingeandcodex 90074e359f [codex] Preserve desktop update state causes (#3473)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:07 -07:00
Julius Marmingeandcodex 6155f5cf64 [codex] Preserve VCS project config error causes (#3474)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:04 -07:00
Julius Marmingeandcodex e3970e755b [codex] Preserve APNs delivery failure context (#3475)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:01 -07:00
Julius Marmingeandcodex 3c246f56b4 [codex] Structure VCS process boundary errors (#3476)
Co-authored-by: codex <[email protected]>
2026-06-20 20:19:59 -07:00
1183 changed files with 121887 additions and 27721 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,64 @@
---
name: ios-debugger-agent
description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including T3 Code Mobile verification.
---
# iOS Debugger Agent
Use the repository-configured `xcodebuildmcp` tools instead of requiring a globally installed Codex plugin. Prefer MCP tools over raw `xcodebuild`, `xcrun`, or `simctl` when the client exposes them.
## Confirm availability
This workflow requires macOS 14.5 or newer, Xcode 16 or newer, and Node.js 18 or newer. The repository pins XcodeBuildMCP in both `.mcp.json` for Claude Code and `.codex/config.toml` for Codex. Project MCP servers may require one-time trust or approval followed by a new session.
If the tools are missing:
1. Confirm the repository is trusted and its project MCP server was approved.
2. Restart or recreate the agent session after approving configuration.
3. Run `npx --yes [email protected] doctor` when the server starts but simulator or UI-automation tools are unavailable. Follow its actionable Xcode or AXe setup guidance.
4. Fall back to the pinned XcodeBuildMCP CLI or native Apple CLIs only when the current agent client cannot expose project MCP tools.
Do not ask contributors to install the OpenAI `build-ios-apps` plugin globally.
## Establish one simulator context
1. Call `session_show_defaults` before discovery, build, launch, or UI work.
2. Call `list_sims` and select one explicit simulator UDID. Prefer a simulator that is already booted; boot an installed simulator when verification requires it, but do not create or download runtimes without user authorization.
3. Call `session_set_defaults` with the project or workspace, scheme, Debug configuration, simulator ID, and bundle identifier when known.
4. Keep every subsequent build, launch, screenshot, log capture, and UI action pinned to that same UDID.
Avoid generic Mac window automation for switching among Simulator windows. Explicit device identity is more reliable.
## Choose build or launch
- Use `build_run_sim` when native source, native dependencies, entitlements, or project configuration changed.
- Use `test_sim` for the smallest relevant native test target or test cases; do not run an entire workspace test matrix routinely.
- Use `launch_app_sim` when a compatible app is already installed and no native rebuild is needed.
- To reuse an existing build artifact, use `get_sim_app_path` or `get_app_bundle_id`, install it with `install_app_sim` when necessary, and then launch it.
- Do not run a build-only action immediately before `build_run_sim` unless the task requires both artifacts.
After launch, call `snapshot_ui` or `screenshot` before interacting. An open Simulator window alone is not evidence that the intended app launched.
## Drive the UI semantically
1. Call `snapshot_ui` to obtain the current accessibility hierarchy and element references.
2. Use only current `elementRef` values whose snapshot entries list the intended action. XcodeBuildMCP `2.6.2` does not accept coordinates for `tap`; when the app exposes no actionable reference, prefer a registered deep link or another app-supported route and otherwise report the accessibility blocker.
3. Refresh with `snapshot_ui` after navigation or layout changes. Element references are snapshot-specific.
4. Use `wait_for_ui` for asynchronous transitions when available rather than fixed sleeps.
5. Capture a final `screenshot` for the state that proves the affected flow.
Use `gesture` or scoped swipe actions when needed. If a gesture is unreliable, return to a known route or relaunch rather than switching to generic desktop automation.
## Capture logs and debug
- Use `start_sim_log_cap` and `stop_sim_log_cap` with the exact bundle identifier for focused runtime logs.
- Use debugger tools only when the task requires runtime diagnosis; attach to the selected simulator and app rather than an ambiguous process.
- Summarize relevant errors instead of returning unbounded logs.
## Clean up
Stop only log captures, debugger sessions, apps, or simulators started for the current test. Leave pre-existing simulators and unrelated sessions alone.
## Upstream
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-debugger-agent`, MIT) and aligned with XcodeBuildMCP `2.6.2` tool names.
@@ -0,0 +1,9 @@
interface:
display_name: "iOS Debugger Agent"
short_description: "Build and drive iOS Simulator apps"
default_prompt: "Use $ios-debugger-agent to build, launch, and inspect the current iOS app on Simulator."
dependencies:
tools:
- type: "mcp"
value: "xcodebuildmcp"
description: "Repository-configured Xcode build, simulator, logging, debugging, and semantic UI tools"
@@ -0,0 +1,21 @@
MIT License
Copyright (c) OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,51 @@
---
name: ios-simulator-browser
description: Stream an explicit iOS Simulator through pinned serve-sim into the T3 Code in-app browser or another agent browser. Use on Apple Silicon macOS when the user should watch simulator verification live or when browser-visible simulator evidence is needed.
---
# iOS Simulator Browser
Use serve-sim as the shared visual feed for an iOS Simulator. Use `ios-debugger-agent` and XcodeBuildMCP semantic UI tools to drive the app; do not treat browser-canvas coordinates as a substitute for missing app accessibility.
## Confirm availability
serve-sim `0.1.45` requires Apple Silicon macOS, Xcode command-line tools, and Node.js 20 or newer. If the host is unsupported, continue with XcodeBuildMCP screenshots and report that live streaming was unavailable.
When running inside T3 Code, use its product-native browser MCP to open the stream. Other agent hosts may use their own browser or preview surface.
Keep serve-sim on its default `127.0.0.1` binding. Do not expose its preview to a LAN or tunnel unless the user explicitly requests that access and the network is trusted; the preview includes a token-gated shell-execution route.
## Start one owned stream
1. Obtain the exact simulator UDID from the iOS build or launch workflow.
2. Check whether an existing serve-sim stream for that UDID belongs to another task. Reuse it only when explicitly shared; never kill another task's stream.
3. Otherwise, clear only a stale stream for that UDID and start the pinned version with scoped cleanup:
```bash
SIMULATOR_ID=<simulator-udid>
cleanup_serve_sim() {
npx --yes [email protected] --kill "$SIMULATOR_ID" >/dev/null 2>&1 || true
}
trap cleanup_serve_sim EXIT INT TERM HUP
cleanup_serve_sim
npx --yes [email protected] "$SIMULATOR_ID"
```
4. Keep the terminal alive and open the exact local URL printed by serve-sim in the agent's browser.
5. Verify that a live simulator frame renders. A loaded wrapper page is not sufficient evidence.
## Observe while driving semantically
- Let the user watch the serve-sim stream while XcodeBuildMCP performs `snapshot_ui`, semantic taps, typing, gestures, and screenshots.
- Keep the browser and Xcode tooling pinned to the same simulator UDID.
- Do not switch to generic desktop automation or browser-canvas clicking merely because the stream is visible.
If the in-app browser explicitly reports that previews are unavailable, do not install unrelated browser automation. Continue through XcodeBuildMCP, capture a simulator screenshot, report the unavailable live stream, and clean up the owned serve-sim process.
## Finish
Stop the long-running terminal and wait for its cleanup trap to finish. If it disappeared without cleanup, run `npx --yes serve-sim@0.1.45 --kill <simulator-udid>` for that exact simulator. Never run an unscoped `--kill`.
## Upstream
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-simulator-browser`, MIT). It invokes serve-sim `0.1.45` under its Apache-2.0 license without vendoring the package.
@@ -0,0 +1,4 @@
interface:
display_name: "iOS Simulator Browser"
short_description: "Stream iOS Simulator in the browser"
default_prompt: "Use $ios-simulator-browser to stream the selected iOS Simulator into the T3 Code in-app browser."
+71
View File
@@ -0,0 +1,71 @@
---
name: test-t3-app
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
---
# Test T3 App
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
## Start an isolated web environment
1. Run commands from the repository root.
2. Choose a base directory that belongs only to the current worktree or test:
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
## Authenticate the browser on the first navigation
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
2. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
## Recover a consumed or expired pairing token
Create another token against the same database and web URL as the running dev server:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
## Finish the test
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
## Troubleshoot predictably
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
@@ -0,0 +1,4 @@
interface:
display_name: "T3 App Testing"
short_description: "Launch and seed isolated T3 test environments"
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
@@ -0,0 +1,58 @@
# SQLite fixtures
Load this reference only when inspecting or seeding local T3 state directly.
## Select the correct database
When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
## Use the helper
List tables:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
```
Inspect current columns before writing a fixture:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "PRAGMA table_info(projection_threads)"
```
Apply a SQL fixture from a file:
```bash
node apps/server/scripts/t3-sqlite-state.ts exec \
--base-dir <base-dir> \
--file /tmp/t3-seed.sql
```
Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
## Seed projection data carefully
The web UI primarily reads these projection tables:
- `projection_projects`
- `projection_threads`
- `projection_thread_messages`
- `projection_thread_activities`
- `projection_thread_sessions`
- `projection_turns`
- `projection_pending_approvals`
- `projection_thread_proposed_plans`
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
+188
View File
@@ -0,0 +1,188 @@
---
name: test-t3-mobile
description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
---
# Test T3 Mobile
Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
## Select a viable platform
Inspect the host and the affected code before launching processes:
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
Do not treat unavailable iOS tooling as a blocker when Android is a valid representative target.
## Choose the lightest valid launch path
- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
The development identity on both platforms is:
- App: `T3 Code Dev`
- Bundle/package identifier: `com.t3tools.t3code.dev`
- URL scheme: `t3code-dev`
Bundle or package presence proves the correct variant, not native compatibility. Reuse it only when the current changes did not alter its Expo SDK, native dependencies, config plugins, entitlements, generated project, or native source.
## Start one disposable T3 environment
Run backend commands from the repository root. Use the ignored, worktree-local `.t3` directory or create a fresh directory with the host OS's temporary-directory mechanism. An explicit base directory stores state in `<base-dir>/userdata`; never point testing at shared `~/.t3` state.
Seed a small number of meaningful Git projects before starting the backend:
```bash
node apps/server/src/bin.ts project add <git-workspace> \
--base-dir <base-dir> \
--title <project-title>
```
Running `project add` before the backend starts gives it exclusive offline database access. If a backend is already running, wait until it is ready so the CLI dispatches through the live server; never run offline mutations concurrently with the server.
Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
Start a headless backend after seeding:
```bash
node apps/server/src/bin.ts serve \
--host 127.0.0.1 \
--port <server-port> \
--base-dir <base-dir> \
--no-browser
```
Use these client origins:
- iOS Simulator: `http://127.0.0.1:<server-port>`
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
## Start or reuse Metro safely
Run Metro from `apps/mobile`.
1. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
2. Never kill another worktree's Metro. Use a free explicit port when necessary.
3. Run `vp run dev:client` on the standard port. For another port, retain the complete development identity:
```bash
APP_VARIANT=development vp exec expo start \
--dev-client \
--scheme t3code-dev \
--clear \
--lan \
--port <metro-port>
```
In PowerShell, set `$env:APP_VARIANT = "development"` first and then run the `vp exec expo start ...` command without the leading assignment.
4. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
### iOS launch
Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
- Workspace: `<repo>/apps/mobile/ios/T3CodeDev.xcworkspace`
- Scheme: `T3CodeDev`
- Configuration: `Debug`
- Simulator ID: the selected UDID
- Bundle ID: `com.t3tools.t3code.dev`
Check the installed client with:
```bash
xcrun simctl get_app_container <simulator-udid> com.t3tools.t3code.dev app
xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
```
Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
### Android launch
Select one running emulator serial from `adb devices` and check the installed client:
```bash
adb -s <emulator-serial> shell pm path com.t3tools.t3code.dev
adb -s <emulator-serial> reverse tcp:<metro-port> tcp:<metro-port>
adb -s <emulator-serial> shell am start -W \
-a android.intent.action.VIEW \
-d '<printed-dev-client-url>' \
com.t3tools.t3code.dev
```
Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
## Pair each client once
Issue a fresh credential against the running backend's exact base directory:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--base-url <mobile-origin> \
--ttl 15m \
--label agent-mobile-<short-device-id>
```
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
```bash
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
adb -s <emulator-serial> shell am start -W \
-a android.intent.action.VIEW \
-d 't3code-dev://connections/new' \
com.t3tools.t3code.dev
```
Run only the command for the selected platform.
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
## Drive and observe the affected flow
### iOS
Use `snapshot_ui` and current element references from XcodeBuildMCP for taps and typing. Stream the same UDID through `ios-simulator-browser` so the user can watch in T3 Code when the host supports it. Use the stream as a visual feed rather than a reason to switch to fragile browser coordinates.
### Android
Prefer semantic Android automation exposed by the current agent host. Otherwise inspect the current hierarchy with `adb shell uiautomator dump`, target stable resource IDs, content descriptions, text, or bounds, and use scoped `adb shell input` actions. Refresh the hierarchy after navigation. Capture the final state with `adb exec-out screencap -p`.
Android does not use serve-sim. Use a browser-compatible Android mirror when the host already provides one; otherwise return focused emulator screenshots as evidence rather than installing unrelated streaming infrastructure during verification.
## Verify and clean up
Exercise only the affected flow on one representative device unless the change specifically concerns platform, OS version, or screen size. Before finishing:
1. Confirm the app connected to the intended disposable environment instead of merely rendering an empty disconnected state.
2. Capture the relevant final state.
3. Remove the disposable environment from T3 Code Dev.
4. Remove any `adb reverse` rule created for this test with `adb -s <emulator-serial> reverse --remove tcp:<metro-port>`.
5. Stop only the serve-sim, Metro, backend, emulator, and log processes started by this test.
6. Remove only base directories and temporary Git repositories deliberately created for this test. Preserve them when they contain useful reproduction evidence.
Keep local verification focused. Do not turn this workflow into a full repository test run.
## Troubleshoot predictable failures
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
@@ -0,0 +1,4 @@
interface:
display_name: "Test T3 Mobile"
short_description: "Test T3 Code on iOS or Android"
default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
+1
View File
@@ -0,0 +1 @@
../.agents/skills
+9
View File
@@ -0,0 +1,9 @@
[mcp_servers.xcodebuildmcp]
enabled = true
required = false
command = "npx"
args = ["--yes", "[email protected]", "mcp"]
startup_timeout_sec = 20.0
[mcp_servers.xcodebuildmcp.env]
XCODEBUILDMCP_ENABLED_WORKFLOWS = "simulator,ui-automation,debugging,logging"
+72
View File
@@ -0,0 +1,72 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+4
View File
@@ -18,6 +18,10 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+113
View File
@@ -0,0 +1,113 @@
name: Mobile EAS Production
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
# Under the fingerprint runtime-version policy the fingerprint must be computed
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
on:
workflow_dispatch:
inputs:
mode:
description: "build (+ auto-submit to TestFlight) or update (OTA)"
required: true
type: choice
default: build
options:
- build
- update
platform:
description: "Target platform"
required: true
type: choice
default: ios
options:
- ios
- android
- all
message:
description: "OTA update message (mode=update only)"
required: false
type: string
jobs:
production:
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
eas update \
--channel production \
--environment production \
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
@@ -0,0 +1,134 @@
name: Mobile Showcase Screenshots
on:
workflow_dispatch:
inputs:
platform:
description: Device platforms to capture
required: true
default: all
type: choice
options:
- all
- ios
- android
appearance:
description: System appearances to capture
required: true
default: both
type: choice
options:
- both
- dark
- light
permissions:
contents: read
env:
NODE_OPTIONS: --max-old-space-size=8192
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload iOS screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: app-store-connect-screenshots
path: artifacts/app-store/screenshots/apple/
if-no-files-found: warn
retention-days: 14
android:
name: Android phone, 7-inch tablet, and 10-inch tablet
if: inputs.platform == 'all' || inputs.platform == 'android'
runs-on: blacksmith-16vcpu-ubuntu-2404
timeout-minutes: 60
env:
T3_SHOWCASE_ANDROID_ABI: x86_64
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Setup Gradle cache
uses: gradle/actions/setup-gradle@v5
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Capture Android showcase
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 36
target: google_apis
arch: x86_64
profile: pixel_7_pro
avd-name: Pixel_10_Pro
cores: 8
ram-size: 4096M
disable-animations: false
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
- name: Validate Google Play assets
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload Android screenshots
if: always()
uses: actions/upload-artifact@v7
with:
name: google-play-screenshots
path: artifacts/app-store/screenshots/google-play/
if-no-files-found: warn
retention-days: 14
+69 -2
View File
@@ -252,10 +252,64 @@ jobs:
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
# job — the Windows artifact then ships a ready WSL backend binary with no
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
build_wsl_node_pty:
name: Build WSL node-pty (linux-x64)
needs: [preflight]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Build node-pty linux-x64 prebuild
shell: bash
run: |
set -euo pipefail
# Resolve node-pty from apps/server (where it's a dependency) and build
# its native binary from source for Linux. node-addon-api resolves from
# node-pty's own dependency tree, so node-gyp has everything it needs.
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
pty_dir="$(dirname "$pty_pkg")"
( cd "$pty_dir" && npx --yes node-gyp rebuild )
mkdir -p wsl-prebuild
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
file wsl-prebuild/pty.node
- name: Upload node-pty linux-x64 prebuild
uses: actions/upload-artifact@v7
with:
name: wsl-node-pty-x64
path: wsl-prebuild/pty.node
if-no-files-found: error
build:
name: Build ${{ matrix.label }}
needs: [preflight, relay_public_config]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
# available to download, but only the Windows matrix entry consumes it. We
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
# build_wsl_node_pty failed; the Windows-only download step below then fails
# that single platform if the prebuild is missing.
needs: [preflight, relay_public_config, build_wsl_node_pty]
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
@@ -323,6 +377,13 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Download WSL node-pty prebuild
if: matrix.platform == 'win'
uses: actions/download-artifact@v7
with:
name: wsl-node-pty-x64
path: wsl-prebuild
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
@@ -476,6 +537,10 @@ jobs:
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
# so the packaged WSL backend ships a ready binary (no first-launch
# compile). Required for a working WSL backend on Windows.
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
@@ -723,6 +788,7 @@ jobs:
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
@@ -806,6 +872,7 @@ jobs:
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=${T3CODE_CLERK_CLI_OAUTH_CLIENT_ID:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
+3
View File
@@ -27,6 +27,9 @@ squashfs-root/
.gstack/
dist-electron/
.electron-runtime/
.showcase/
apps/mobile/.showcase/
artifacts/app-store/screenshots/
node_modules/
.alchemy/
*.log
@@ -43,12 +43,23 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Dependency acquisition and runtime boundaries
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -56,6 +67,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -73,4 +87,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
+11
View File
@@ -0,0 +1,11 @@
{
"mcpServers": {
"xcodebuildmcp": {
"command": "npx",
"args": ["--yes", "[email protected]", "mcp"],
"env": {
"XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
}
}
}
}
+257
View File
@@ -0,0 +1,257 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plan: seamless `npx t3 connect` for remote boxes</title>
<style>
:root {
--bg: #000;
--fg: #fff;
--muted: #a3a3a3;
--surface: #121212;
--surface2: #1a1a1a;
--border: #2a2a2a;
--accent: #7c9cff;
--green: #4ade80;
--amber: #fbbf24;
--red: #f87171;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--fg);
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
h1 { font-size: 30px; line-height: 1.25; margin: 0 0 8px; }
h2 { font-size: 21px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--border); }
h3 { font-size: 16px; margin: 24px 0 8px; }
p, li { color: #e5e5e5; }
.sub { color: var(--muted); margin: 0 0 24px; }
code, pre {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 13.5px;
}
code { background: var(--surface2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }
pre {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 16px;
overflow-x: auto;
line-height: 1.5;
}
pre code { background: none; border: none; padding: 0; }
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 18px 20px;
margin: 16px 0;
}
.card h3 { margin-top: 0; }
table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14.5px; }
th, td { text-align: left; padding: 8px 12px; border: 1px solid var(--border); vertical-align: top; }
th { background: var(--surface2); font-weight: 600; }
td code { white-space: nowrap; }
.pill {
display: inline-block; font-size: 12px; font-weight: 600; border-radius: 999px;
padding: 2px 10px; margin-right: 6px; vertical-align: 2px;
}
.pill.core { background: #1e2a4a; color: var(--accent); }
.pill.new { background: #14301e; color: var(--green); }
.pill.later { background: #33270e; color: var(--amber); }
.ok { color: var(--green); }
.warn { color: var(--amber); }
.no { color: var(--red); }
ul { padding-left: 22px; }
li { margin: 4px 0; }
.terminal {
background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px;
padding: 16px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 13.5px; line-height: 1.65; color: #d4d4d4; overflow-x: auto;
}
.terminal .dim { color: #737373; }
.terminal .g { color: var(--green); }
.terminal .b { color: var(--accent); }
figure { margin: 24px 0; }
figcaption { color: var(--muted); font-size: 13px; margin-top: 8px; text-align: center; }
svg text { font-family: -apple-system, "Segoe UI", sans-serif; }
a { color: var(--accent); }
.kv { color: var(--muted); font-size: 13.5px; }
</style>
</head>
<body>
<main>
<h1>Seamless <code>npx t3 connect</code> for remote boxes</h1>
<p class="sub">Design principle: <strong>the smallest diff that ships the UX.</strong> No relay/infra changes, no new backend surface, no new auth primitives &mdash; every step reuses code that already exists. One PR, built as four phases with clear commit boundaries &mdash; each phase compiles, passes tests, and leaves the product working, so the PR reviews commit-by-commit. (Phase 4, web-triggered update, is an optional follow-up PR.)</p>
<div class="terminal">
$ npx t3 connect<br><br>
To set up T3 Connect, open this URL and sign in:<br>
&nbsp;&nbsp;<span class="b">https://app.t3.codes/connect#B64URL_STATE_AND_CHALLENGE</span><br><br>
Enter your authentication code: <span class="dim">[code]</span><br><br>
<span class="g">Connected as [email protected]!</span><br><br>
Run T3 Code in the background whenever this machine boots? (y/n): y<br><br>
<span class="g">T3 Code is set up and ready to go.</span>
</div>
<h2>Why this is a small change</h2>
<p>The entire <code>t3 connect</code> data plane already works: Clerk PKCE token exchange, encrypted secret store, cloudflared relay-client install, relay environment linking, DPoP tokens. The <em>only</em> broken piece on an SSH box is the redirect: <code>CliTokenManager.login()</code> hardcodes a loopback callback (<code>http://127.0.0.1:34338/callback</code>) that requires a browser on the same machine.</p>
<p>We swap that one leg for a hosted out-of-band authorization page and keep everything else. Because PKCE's <code>code_verifier</code> never leaves the box, the displayed one-time code is useless to anyone who sees it &mdash; no new token-minting or storage is needed anywhere.</p>
<div class="card">
<h3>Reused as-is (zero changes)</h3>
<ul>
<li><code>exchangeToken()</code> PKCE exchange &mdash; <code>apps/server/src/cloud/CliTokenManager.ts:147</code></li>
<li>Token persistence in <code>ServerSecretStore</code> (<code>cloud-cli-oauth-token</code>)</li>
<li><code>acquireRelayClientForLink()</code> cloudflared install + progress &mdash; <code>cli/connect.ts:146</code></li>
<li><code>CliState.setCliDesiredCloudLink()</code> + server-side provisioning on start</li>
<li>All relay endpoints (<code>infra/relay</code>) and contracts &mdash; <strong>untouched</strong></li>
<li>Existing subcommands <code>login/link/status/unlink/logout</code> &mdash; semantics unchanged</li>
<li>Web app Clerk session + hosted-page precedent (<code>routes/pair.tsx</code>, <code>hostedPairing.ts</code>)</li>
</ul>
</div>
<h2>Auth flow (hosted out-of-band OAuth, Clerk PKCE)</h2>
<figure>
<svg viewBox="0 0 820 470" width="100%" role="img" aria-label="Sequence diagram of the out-of-band OAuth flow">
<!-- lanes -->
<rect x="20" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<rect x="300" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<rect x="580" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<text x="130" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Remote box &#8212; t3 CLI</text>
<text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop &#8212; app.t3.codes</text>
<text x="690" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Clerk</text>
<line x1="130" y1="60" x2="130" y2="450" stroke="#2a2a2a"/>
<line x1="410" y1="60" x2="410" y2="450" stroke="#2a2a2a"/>
<line x1="690" y1="60" x2="690" y2="450" stroke="#2a2a2a"/>
<!-- 1: generate + print -->
<rect x="30" y="80" width="200" height="34" rx="6" fill="#1e2a4a"/>
<text x="130" y="101" fill="#7c9cff" font-size="12.5" text-anchor="middle">1. gen verifier + challenge + state</text>
<!-- 2: user opens URL -->
<line x1="130" y1="140" x2="404" y2="140" stroke="#7c9cff" stroke-dasharray="5 4"/>
<polygon points="404,140 394,135 394,145" fill="#7c9cff"/>
<text x="267" y="132" fill="#a3a3a3" font-size="12.5" text-anchor="middle">2. user opens /connect#&#123;state,challenge&#125;</text>
<!-- 3: redirect to clerk -->
<line x1="410" y1="185" x2="684" y2="185" stroke="#e5e5e5"/>
<polygon points="684,185 674,180 674,190" fill="#e5e5e5"/>
<text x="547" y="177" fill="#a3a3a3" font-size="12.5" text-anchor="middle">3. sign in &#8594; /oauth/authorize (PKCE)</text>
<!-- 4: redirect back with code -->
<line x1="690" y1="230" x2="416" y2="230" stroke="#e5e5e5"/>
<polygon points="416,230 426,225 426,235" fill="#e5e5e5"/>
<text x="553" y="222" fill="#a3a3a3" font-size="12.5" text-anchor="middle">4. redirect /connect/callback?code&amp;state</text>
<!-- 5: page shows code -->
<rect x="310" y="252" width="200" height="34" rx="6" fill="#14301e"/>
<text x="410" y="273" fill="#4ade80" font-size="12.5" text-anchor="middle">5. shows account + authorization code</text>
<!-- 6: user enters code -->
<line x1="410" y1="316" x2="136" y2="316" stroke="#7c9cff" stroke-dasharray="5 4"/>
<polygon points="136,316 146,311 146,321" fill="#7c9cff"/>
<text x="273" y="308" fill="#a3a3a3" font-size="12.5" text-anchor="middle">6. user enters code in terminal</text>
<!-- 7: token exchange -->
<line x1="130" y1="360" x2="684" y2="360" stroke="#e5e5e5"/>
<polygon points="684,360 674,355 674,365" fill="#e5e5e5"/>
<text x="407" y="352" fill="#a3a3a3" font-size="12.5" text-anchor="middle">7. POST /oauth/token &#123;code + verifier&#125; &#8594; access/refresh tokens</text>
<!-- 8: done -->
<rect x="30" y="392" width="200" height="46" rx="6" fill="#14301e"/>
<text x="130" y="411" fill="#4ade80" font-size="12.5" text-anchor="middle">8. store token, set desired link,</text>
<text x="130" y="427" fill="#4ade80" font-size="12.5" text-anchor="middle">install relay client &#8594; Connected!</text>
</svg>
<figcaption>The verifier never leaves the box (steps 1&#8594;7), so the authorization code is worthless if observed. state/challenge ride the URL fragment &mdash; they are not secrets.</figcaption>
</figure>
<div class="card">
<h3>Details that keep it simple</h3>
<ul>
<li><strong>Stateless URL, no short-link service.</strong> The <code>/connect</code> page reads <code>state</code> + <code>code_challenge</code> from the URL fragment and builds the Clerk authorize URL client-side. ~100-char URL &mdash; fine to transfer into an SSH session.</li>
<li><strong>State check without a backend:</strong> the callback page displays one authorization blob of <code>code.state</code>; the CLI splits it and verifies <code>state</code> matches what it generated. One line on each side, preserves the loopback flow's CSRF check.</li>
<li><strong>Phishing is addressed with copy, not code:</strong> the callback page shows <em>which account</em> is being connected ("Connecting as theo@&hellip;") and warns: <em>"Only enter this code in a terminal session you started yourself."</em> No mechanism needed.</li>
<li><strong>Code expiry is a non-issue:</strong> Clerk auth codes live 10 minutes &mdash; the same timeout the existing loopback flow already uses. Wrong/expired code &#8594; friendly retry that reprints the URL.</li>
<li><strong>One external config step:</strong> register <code>https://app.t3.codes/connect/callback</code> as an allowed redirect URI on the existing Clerk CLI OAuth client. No new client, no new scopes.</li>
</ul>
</div>
<h2>The phases (one PR, one commit each)</h2>
<p class="kv">Ordering is dependency order: each phase is independently revertable and the tree is green at every boundary. Phases 1&ndash;3 are the PR; phase 4 ships separately later.</p>
<table>
<tr><th style="width:1%">Phase</th><th>Scope</th><th>Files</th><th style="width:1%">~LOC</th></tr>
<tr>
<td><span class="pill core">1</span></td>
<td><strong>Hosted code page</strong> (web-only, purely additive, zero risk). Two static routes modeled on <code>pair.tsx</code>: <code>/connect</code> (ensure Clerk session, then client-side redirect to authorize &mdash; it's a static SPA, no server 302) and <code>/connect/callback</code> (validate params, show account + copyable code + safety warning). Both routes guard against non-hosted deployments &mdash; redirect to <code>/</code> unless <code>isHostedStaticApp()</code>, same pattern as <code>pair.tsx</code>, since this bundle also ships in local instances. Plus the Clerk dashboard redirect-URI entry.</td>
<td><code>apps/web/src/routes/connect.tsx</code><br><code>apps/web/src/routes/connect.callback.tsx</code></td>
<td>~200</td>
</tr>
<tr>
<td><span class="pill core">2</span></td>
<td><strong>CLI out-of-band OAuth flow + single command.</strong> Add an out-of-band OAuth login path to <code>CliTokenManager</code> (print URL, <code>Prompt.text</code> for the code, reuse <code>exchangeToken</code>). Make bare <code>t3 connect</code> a handler = login + link (subcommands untouched). Auto-pick headless mode inside SSH sessions (<code>SSH_CONNECTION</code>/<code>SSH_TTY</code> &mdash; nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop &mdash; no regression.</td>
<td><code>cloud/CliTokenManager.ts</code> (+60)<br><code>cloud/publicConfig.ts</code> (+10)<br><code>cli/connect.ts</code> (+60)</td>
<td>~150</td>
</tr>
<tr>
<td><span class="pill new">3</span></td>
<td><strong>Background on boot &mdash; Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/&lt;v&gt;</code> + <code>current</code> symlink, systemd <em>user</em> unit with absolute node/t3 paths, <code>enable-linger</code>. y/n prompt at the end of <code>connect</code>; teardown in <code>logout</code>. Install and service-start failures must land in a log file (under <code>~/.t3/userdata/logs/</code>) whose path is printed at connect time &mdash; systemd user units fail invisibly otherwise. Unit-file generation is pure string-building &#8594; trivially testable. macOS launchd / Windows follow as 3b/3c only if wanted.</td>
<td><code>cloud/bootService.ts</code> (new)<br><code>cli/connect.ts</code> (+prompt/teardown)</td>
<td>~250</td>
</tr>
<tr>
<td><span class="pill later">4</span></td>
<td><strong>Web-triggered update</strong> (optional follow-up PR; not part of this one, not needed for the core UX). Web detects <code>daemon version &lt; latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command &mdash; client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified &mdash; that would be RCE). Stage install &#8594; verify &#8594; atomic symlink swap &#8594; <code>systemctl --user restart</code>. Progress streams reuse the <code>RelayClientInstallProgressEvent</code> pattern.</td>
<td>web banner + one control command + daemon update routine</td>
<td>later</td>
</tr>
</table>
<h3>Runtime layout (phase 3)</h3>
<pre><code>~/.t3/runtime/
├── versions/0.0.27/ &larr; npm install --prefix (gets native deps right: node-pty etc.)
└── current -> versions/0.0.27
~/.config/systemd/user/t3code.service &larr; ExecStart=/abs/path/node .../current/.../t3 serve
loginctl enable-linger $USER &larr; survives SSH logout / reboot</code></pre>
<p class="kv">Why a real <code>npm install</code> and not "reuse the npx binary": the npx cache is ephemeral and <code>t3</code> ships native deps (<code>node-pty</code>, <code>@ff-labs/fff-node</code>) that need per-platform prebuilds. Why pinned and not <code>npx t3@latest</code> in the unit: a boot-time registry fetch means the box may simply not come up (network down, PATH-less systemd env, nvm). Deterministic boot; updates happen out-of-band (phase 4 follow-up) or by re-running <code>npx t3 connect</code>.</p>
<h2>Explicitly not doing</h2>
<ul>
<li><span class="no">&#10007;</span> Relay / <code>infra</code> / contracts changes &mdash; none, in any phase</li>
<li><span class="no">&#10007;</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) &mdash; only matters for hand-typing; revisit if ever needed</li>
<li><span class="no">&#10007;</span> RFC 8628 device grant &mdash; wrong UX direction, unverified Clerk support</li>
<li><span class="no">&#10007;</span> Auto-update loop in the daemon &mdash; web-triggered only (phase 4 follow-up), user stays in control</li>
<li><span class="no">&#10007;</span> Project auto-registration &mdash; workspace assumed set up; the web UI handles the rest</li>
<li><span class="no">&#10007;</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
</ul>
<h2>Risks &amp; checks</h2>
<ul>
<li><span class="warn">&#9888;</span> <strong>Clerk redirect URI:</strong> confirm the CLI OAuth client accepts the hosted redirect and that the token endpoint honors PKCE exchange for codes issued to it. Verify in staging before the phase 2 commit. <em>(Only external dependency in the plan.)</em></li>
<li><span class="warn">&#9888;</span> <strong>systemd user env is minimal:</strong> always write absolute paths for node + t3 into the unit; never rely on PATH. Service failures are invisible by default &mdash; hence the phase 3 requirement to log to a printed file path.</li>
<li><span class="warn">&#9888;</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on &mdash; that's the feature, but say it.</li>
<li><span class="ok">&#10003;</span> Re-running <code>connect</code> when linked &#8594; idempotent: refresh token, re-confirm service, done.</li>
</ul>
<h2>Decision log</h2>
<ul class="kv">
<li>Auth: hosted out-of-band OAuth redirect on Clerk PKCE (not relay-brokered pairing, not device grant) &mdash; chosen for minimal new surface.</li>
<li>URL: stateless static page, no backend short-link.</li>
<li>Service: real per-user login service (systemd user + linger first); detect + offer install, never silent.</li>
<li>Binary: pinned managed runtime under <code>~/.t3</code>; interactive <code>npx</code> usage untouched.</li>
<li>Updates: not always-latest; web UI surfaces available updates with one-click trigger (phase 4 follow-up).</li>
<li>Delivery: one PR with a commit per phase (green tree at every boundary), not separate PRs.</li>
<li>Workspace: assumed already set up; no auto-registration.</li>
</ul>
</main>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
vp staged
+24 -20
View File
@@ -2,27 +2,33 @@
## Task Completion Requirements
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
- If changing native mobile code, `vp run lint:mobile` must also pass.
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
- Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Project Snapshot
## Verifying Changes in the Browser
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
Starting a dev server to verify changes is expected and allowed:
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
- `T3CODE_DEV_INSTANCE=<worktree-name> bun run dev` runs an isolated instance
with deterministic port offsets (server base `13773`, web base `5733`; the
runner probes for free ports and prints the chosen pair).
- On localhost dev servers the web UI authenticates automatically — no pairing
code needed. Just load the printed web port (e.g. `http://localhost:5733`).
This applies to fresh/headless browser profiles too.
- Dev instances sharing the default `T3CODE_HOME` (`~/.t3`) share state under
`~/.t3/dev`; a browser session carries across instances on the same hostname.
Use `localhost` consistently — it does not share cookies with `127.0.0.1`.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
See `docs/reference/scripts.md` for parallel-instance details and
`docs/cloud/environment-auth.md` for how dev auto-auth is secured.
## Package Roles
@@ -35,7 +41,6 @@ Long term maintainability is a core priority. If you add new functionality, firs
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
@@ -47,8 +52,7 @@ agents.
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one
configured repository.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
+3
View File
@@ -0,0 +1,3 @@
{
"expo": {}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.27",
"version": "0.0.28",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+82 -28
View File
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const LAUNCHER_VERSION = 14;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
@@ -204,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
{
@@ -261,11 +278,25 @@ function readJson(path) {
}
}
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
const launcherExecutableName = `${displayName} Launcher`;
return {
launcherExecutableName,
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
};
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
const launcherBinaryPath = isDevelopment
? developmentPaths.launcherBinaryPath
: runtimeElectronBinaryPath;
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
@@ -282,12 +313,19 @@ function buildMacLauncher(electronBinaryPath) {
const currentMetadata = readJson(metadataPath);
if (
NodeFS.existsSync(targetBinaryPath) &&
NodeFS.existsSync(launcherBinaryPath) &&
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
@@ -299,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
recursive: true,
verbatimSymlinks: true,
});
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchMainBundleInfoPlist(
targetAppBundlePath,
iconPath,
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
// Keep Electron's native executable inside the branded bundle. Launching the
// node_modules copy makes macOS associate the process (and Dock label) with
// Electron.app even though this bundle's Info.plist has the T3 Code name.
// Its conventional executable name also keeps Electron's default-app runtime
// in development mode instead of making app.isPackaged report true.
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
@@ -336,10 +383,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
if (hostPlatform !== "darwin") {
return electronBinaryPath;
@@ -356,13 +400,23 @@ export function resolveElectronLaunchCommand(args = []) {
};
}
export function resolveElectronBinaryPath({
ensureRuntime = ensureElectronRuntime,
createRequire = NodeModule.createRequire,
moduleUrl = import.meta.url,
} = {}) {
ensureRuntime();
const require = createRequire(moduleUrl);
return require("electron");
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
@@ -0,0 +1,81 @@
import { assert, describe, it } from "vite-plus/test";
import {
makeDevelopmentLauncherScript,
resolveElectronBinaryPath,
resolveMacLauncherPaths,
} from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
it("repairs Electron before loading the package entrypoint", () => {
const calls = [];
const electronPath = resolveElectronBinaryPath({
ensureRuntime: () => {
calls.push("ensure");
},
createRequire: () => (specifier) => {
calls.push(`require:${specifier}`);
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
},
moduleUrl: import.meta.url,
});
assert.equal(
electronPath,
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
const paths = resolveMacLauncherPaths(
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
"T3 Code (Dev)",
);
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
assert.equal(
paths.launcherBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
);
assert.equal(
paths.runtimeElectronBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
);
const script = makeDevelopmentLauncherScript({
electronBinaryPath: paths.runtimeElectronBinaryPath,
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {},
});
assert.include(
script,
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
);
assert.notInclude(script, "node_modules/electron");
});
});
+32 -5
View File
@@ -13,7 +13,8 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
@@ -23,6 +24,7 @@ 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";
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
@@ -135,11 +137,14 @@ 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 pool = yield* DesktopBackendPool.DesktopBackendPool;
const primaryBackend = yield* pool.primary;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* logBootstrapInfo("bootstrap start");
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
@@ -193,8 +198,20 @@ const bootstrap = Effect.gen(function* () {
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
yield* backendManager.start;
// In wsl-only mode the renderer is served by the WSL backend, which can be
// slow to cold-boot — show a "Connecting to WSL" splash immediately so the
// app feels responsive instead of presenting no window until WSL is ready.
// (Dual mode opens fast off the Windows primary, so no splash there.)
if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
yield* desktopWindow.showConnectingSplash;
}
yield* primaryBackend.start;
yield* logBootstrapInfo("bootstrap backend start requested");
// Bring up the WSL backend if the user previously enabled it. The
// primary is already starting; reconcile fires off the WSL register
// in parallel rather than blocking primary readiness on a possibly
// slow first wsl.exe spawn.
yield* Effect.forkScoped(wslBackend.reconcile);
}
}).pipe(Effect.withSpan("desktop.bootstrap"));
@@ -241,10 +258,20 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
// Stop every backend in the pool, not just the primary. The
// electronApp.quit() path can race ahead of the layer-scope
// cascade, so leaving the WSL instance for its parent scope
// finalizer means it gets hard-killed by the OS instead of
// receiving SIGTERM + grace. Stops run concurrently.
const instances = yield* pool.list;
yield* Effect.forEach(instances, (instance) => instance.stop(), {
concurrency: "unbounded",
});
}).pipe(Effect.ensuring(shutdown.markComplete)),
);
yield* startup;
@@ -1,122 +0,0 @@
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 Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
const environmentLayer = DesktopEnvironment.layer({
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,
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
const withOutputLog = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
messages: Array<ReadonlyArray<unknown>>,
) => {
const logger = Logger.make(({ message }) => {
messages.push(Array.isArray(message) ? message : [message]);
});
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
);
return effect.pipe(Effect.provide(outputLogLayer));
};
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
?.error;
describe("DesktopBackendOutputLog", () => {
it.effect("logs setup failures with the log path and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
description: "private setup diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.fail(cause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private setup diagnostic");
}),
fileSystemLayer,
messages,
);
});
it.effect("logs record write failures with the operation and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const missingCause = PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "stat",
pathOrDescriptor: LOG_FILE_PATH,
});
const writeCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFile",
pathOrDescriptor: LOG_FILE_PATH,
description: "private write diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.void,
stat: () => Effect.fail(missingCause),
readDirectory: () => Effect.succeed([]),
writeFile: () => Effect.fail(writeCause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
assert.equal(error.operation, "write-record");
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, writeCause);
assert.equal(
error.message,
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private write diagnostic");
}),
fileSystemLayer,
messages,
);
});
});
@@ -1,385 +0,0 @@
import * as Context from "effect/Context";
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 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 DesktopEnvironment from "./DesktopEnvironment.ts";
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly filePath: string;
readonly writeBytes: (
chunk: Uint8Array,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
readonly writeText: (
chunk: string,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
"DesktopLogFileWriterRecoveryError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
recoveryCause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
"DesktopBackendOutputLogSetupError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
"DesktopBackendOutputLogWriteError",
{
operation: Schema.Literals(["encode-record", "write-record"]),
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
}
}
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
"DesktopBackendConsoleWriteError",
{
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to mirror desktop backend output to ${this.streamName}.`;
}
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
{
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
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: DesktopBackendOutputLog["Service"] = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, PlatformError.PlatformError> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
}),
);
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 recoverCurrentSize = (
cause: PlatformError.PlatformError,
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.matchEffect({
onFailure: (recoveryCause) =>
Effect.fail(
new DesktopLogFileWriterRecoveryError({
logFilePath: input.filePath,
cause,
recoveryCause,
}),
),
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
}),
);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory);
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 });
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source);
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem.exists(input.filePath);
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
});
const writeBytes = (
chunk: Uint8Array,
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
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.catchTags({
PlatformError: recoverCurrentSize,
}),
),
);
};
yield* pruneOverflowBackups;
return {
filePath: input.filePath,
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.try({
try: () => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
},
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
}).pipe(
Effect.catchTags({
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
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,
}).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "encode-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
yield* logFile.writeText(`${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "write-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
},
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
const writer = yield* makeRotatingLogFileWriter({
filePath: logFilePath,
}).pipe(
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
Effect.map(Option.some),
Effect.catchTags({
DesktopBackendOutputLogSetupError: (error) =>
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
const service = 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 DesktopBackendOutputLog["Service"],
});
return DesktopBackendOutputLog.of(service);
});
export const layer = Layer.effect(DesktopBackendOutputLog, make);
@@ -53,13 +53,16 @@ describe("DesktopEnvironment", () => {
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.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
assert.equal(
environment.savedEnvironmentRegistryPath,
"/tmp/t3/userdata/saved-environments.json",
);
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("derives production state paths under userdata", () =>
it.effect("stores production state under userdata in an explicit home", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
@@ -95,6 +98,19 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
{},
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
);
const production = yield* makeEnvironment();
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
}),
);
it.effect("uses a configured app user model id override", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
+6 -2
View File
@@ -147,7 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
: 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 configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
const stateDir = path.join(
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const resourcesPath = input.resourcesPath;
+7 -1
View File
@@ -73,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
function* (): Effect.fn.Return<
void,
never,
DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
> {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.flushMainWindowBounds;
yield* shutdown.request;
yield* shutdown.awaitComplete;
},
@@ -125,7 +125,8 @@ describe("DesktopObservability", () => {
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
@@ -145,6 +146,7 @@ describe("DesktopObservability", () => {
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
assert.equal(boundary.annotations.instanceId, "primary");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
@@ -152,6 +154,7 @@ describe("DesktopObservability", () => {
assert.equal(output.level, "INFO");
assert.equal(output.annotations.component, "desktop-backend-child");
assert.equal(output.annotations.runId, "test-run");
assert.equal(output.annotations.instanceId, "primary");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
}).pipe(
+376 -8
View File
@@ -1,20 +1,65 @@
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
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 Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
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 { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
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>;
}
// Factory for per-instance backend output logs. `forInstance(id)` returns
// a writer that targets a distinct rotating log file — the primary
// instance keeps `server-child.log` so the historical path stays stable
// for ops; other instances get `server-child-<sanitized-id>.log`.
//
// Writers are cached per id within a single factory instance so repeated
// `forInstance` calls (e.g. during a backend restart that re-resolves
// services) reuse the same rotating writer rather than racing each other
// on the same file.
export class DesktopBackendOutputLogFactory extends Context.Service<
DesktopBackendOutputLogFactory,
{
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
}
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export type DesktopLogAnnotations = Record<string, unknown>;
@@ -50,7 +95,166 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.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);
@@ -70,6 +274,170 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
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 PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
const backendLogFilePathForInstance = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
): string => {
// Primary keeps the historical "server-child.log" path so ops scripts
// and packaged-build log inspection still find it where it always lived.
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
return environment.path.join(environment.logDir, "server-child.log");
}
const sanitized = sanitizeInstanceIdForFileName(id);
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
};
// Just the IO sink. Cacheable by resolved file path so two ids that
// sanitize to the same filename share a single RotatingLogFileWriter
// (no race on currentSize tracking). Splitting the sink off from the
// per-call shape lets the shape annotate writes with the *caller's*
// id rather than whatever id created the cached writer first.
const makeBackendOutputSinkForInstance = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
): Effect.Effect<
Option.Option<RotatingLogFileWriter>,
never,
FileSystem.FileSystem | Path.Path | Scope.Scope
> =>
makeRotatingLogFileWriter({
filePath: backendLogFilePathForInstance(environment, id),
}).pipe(Effect.option);
const makeBackendOutputLogShape = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
sink: Option.Option<RotatingLogFileWriter>,
): DesktopBackendOutputLogShape =>
Option.match(sink, {
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,
instanceId: id,
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,
instanceId: id,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
});
const backendOutputLogFactoryLayer = Layer.effect(
DesktopBackendOutputLogFactory,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const factoryScope = yield* Scope.Scope;
// Per-file-path cache of the IO sink only. The per-call shape
// wraps the sink with the caller's instance id so a cache hit on
// a path collision (e.g. "wsl:default" and "wsl_default" both
// resolve to server-child-wsl_default.log) doesn't attribute the
// second caller's writes to the first caller's id. Each sink pins
// itself to the factory's scope so all log resources tear down
// together at app exit. Mutex serializes concurrent first-time
// lookups for the same file path.
const cacheRef = yield* SynchronizedRef.make<
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
>(new Map());
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
const cacheKey = backendLogFilePathForInstance(environment, id);
const cached = cache.get(cacheKey);
if (cached !== undefined) {
return Effect.succeed([
makeBackendOutputLogShape(environment, id, cached),
cache,
] as const);
}
return makeBackendOutputSinkForInstance(environment, id).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Scope.provide(factoryScope),
Effect.map((sink) => {
const next = new Map(cache);
next.set(cacheKey, sink);
return [
makeBackendOutputLogShape(environment, id, sink),
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const;
}),
);
});
return DesktopBackendOutputLogFactory.of({
forInstance: (id) => makeForId(id),
});
}),
);
const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
@@ -82,8 +450,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
@@ -101,8 +469,8 @@ const tracerLayer = Layer.unwrap(
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
@@ -113,7 +481,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
DesktopBackendOutputLogModule.layer,
backendOutputLogFactoryLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
@@ -4,13 +4,19 @@ 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 ManagedRuntime from "effect/ManagedRuntime";
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 { ChildProcessSpawner } from "effect/unstable/process";
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";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
observability: Schema.Struct({
@@ -45,19 +51,22 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
function makeEnvironmentLayer(
baseDir: string,
options?: {
readonly appPath?: string;
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly platform?: NodeJS.Platform;
readonly resourcesPath?: string;
},
) {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
platform: options?.platform ?? "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
appPath: options?.appPath ?? "/repo",
isPackaged: options?.isPackaged ?? true,
resourcesPath: "/missing/resources",
resourcesPath: options?.resourcesPath ?? "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
@@ -75,6 +84,14 @@ function makeEnvironmentLayer(
);
}
const restoreEnv = (name: string, value: string | undefined) => {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
};
const withHarness = <A, E, R>(
effect: Effect.Effect<
A,
@@ -95,6 +112,8 @@ const withHarness = <A, E, R>(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
),
),
@@ -102,14 +121,14 @@ const withHarness = <A, E, R>(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
describe("DesktopBackendConfiguration", () => {
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
it.effect("resolvePrimary produces 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;
const first = yield* configuration.resolvePrimary;
const second = yield* configuration.resolvePrimary;
assert.equal(first.executablePath, process.execPath);
assert.equal(first.entryPath, environment.backendEntryPath);
@@ -133,7 +152,167 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("includes persisted backend observability endpoints when present", () =>
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const primary = yield* configuration.resolvePrimary;
const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
}),
),
);
it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
const observedDistros: Array<string | null> = [];
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolveWsl({ port: 5000, distro: null });
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [
{ name: "Debian", isDefault: false, version: 2 },
{ name: "Ubuntu", isDefault: true, version: 2 },
],
windowsToWslPath: (distro) => {
observedDistros.push(distro);
return Option.some("/repo/apps/server/dist/bin.mjs");
},
ensureNodePty: (distro) => {
observedDistros.push(distro);
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
},
getDistroIp: (distro) => {
observedDistros.push(distro);
return Option.some("172.27.0.99");
},
}),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: baseDir,
platform: "win32",
resourcesPath: baseDir,
}),
),
),
),
);
assert.equal(config.runningDistro, "Ubuntu");
assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
windowsToWslPath: () => Option.some(linuxEntryPath),
ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
getDistroIp: () => Option.some("172.27.0.99"),
}),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: baseDir,
devServerUrl,
isPackaged: true,
platform: "win32",
resourcesPath: baseDir,
}),
),
),
),
);
assert.equal(config.bootstrapDelivery, "stdin");
assert.deepEqual(config.args, [
"-d",
"Ubuntu",
"--exec",
"env",
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
nodePath,
linuxEntryPath,
"--bootstrap-fd",
"0",
"--dev-url",
devServerUrl,
]);
assert.notInclude(config.args, "bash");
assert.notInclude(config.args, "/bin/sh");
assert.notInclude(config.args, "-c");
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
// Resolve both before any token is cached, concurrently, so the
// generate step (a yield point) can interleave. The atomic
// get-or-create must still hand both the same token; a non-atomic
// Ref would let each generate its own and break the shared-token
// invariant.
const [primary, wsl] = yield* Effect.all(
[configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
{ concurrency: "unbounded" },
);
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
}),
),
);
it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
withHarness(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -153,18 +332,18 @@ describe("DesktopBackendConfiguration", () => {
}),
);
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
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", () =>
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
@@ -175,10 +354,11 @@ describe("DesktopBackendConfiguration", () => {
it.effect("logs structured context when persisted observability settings cannot be read", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const settingsPath = `${baseDir}/userdata/settings.json`;
const settingsPath = path.join(baseDir, "userdata", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -198,12 +378,14 @@ describe("DesktopBackendConfiguration", () => {
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolve;
return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
@@ -228,7 +410,7 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("captures backend output in development so child process logs can be persisted", () =>
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -237,12 +419,14 @@ describe("DesktopBackendConfiguration", () => {
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
const config = yield* configuration.resolvePrimary;
assert.equal(config.captureOutput, true);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
isPackaged: false,
@@ -254,4 +438,362 @@ describe("DesktopBackendConfiguration", () => {
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const previousWslEnv = process.env.WSLENV;
const previousOpenAiKey = process.env.OPENAI_API_KEY;
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
try {
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
process.env.OPENAI_API_KEY = "openai-key";
process.env.ANTHROPIC_API_KEY = "anthropic-key";
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
assert.equal(config.executablePath, "wsl.exe");
assert.equal(config.bootstrap.port, 5050);
// Binds to 0.0.0.0 inside WSL so the backend is reachable via
// both wslhost-forwarded localhost and the distro's eth0 IP.
assert.equal(config.bootstrap.host, "0.0.0.0");
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
// httpBaseUrl uses the resolved distro IP from the test stub,
// not localhost — the renderer reaches the backend directly to
// avoid relying on wslhost forwarding.
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
assert.equal(config.env.OPENAI_API_KEY, "openai-key");
assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
// The existing WSLENV is preserved byte-for-byte (note the empty
// "::" segment survives — WSL ignores it, so we don't normalize
// it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
// already declared, so it isn't forwarded twice.
assert.equal(
config.env.WSLENV,
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
getDistroIp: () => Option.some("172.27.0.99"),
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
} finally {
restoreEnv("WSLENV", previousWslEnv);
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
}
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
// wsl-only is persisted but WSL is unavailable, so the primary must
// not spawn wsl.exe (which would loop on preflight failures while the
// Connections backend control is hidden). Resolve the Windows primary.
assert.equal(config.executablePath, process.execPath);
assert.equal(config.bootstrap.t3Home, environment.baseDir);
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
() =>
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.resolvePrimary;
const failure = Option.getOrThrow(config.preflightFailure);
assert.equal(config.executablePath, "wsl.exe");
assert.isTrue(failure.fatal);
assert.include(failure.reason, "Removed-Distro");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Removed-Distro",
}),
),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
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.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isFalse(failure.fatal);
assert.equal(failure.retryLimit, 12);
assert.include(failure.reason, "timed out");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
reason: "wsl.exe --list --verbose timed out",
}),
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
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.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isTrue(failure.fatal);
assert.include(failure.reason, "missing server entry");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
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.resolveWsl({ port: 5050, distro: "Removed-Distro" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isTrue(failure.fatal);
assert.include(failure.reason, "Removed-Distro");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
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 label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "WSL (Ubuntu)");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "Local environment");
}),
),
);
it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
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;
// Mirrors the resolvePrimary fall-back: the label must follow the
// backend that actually resolves, not the persisted preference, so the
// env switcher can't show "WSL" for a Windows backend.
const label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "Windows");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
// getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
// primary instance's lazy label through Effect.runSync. The label chains
// to wslEnvironment.isAvailable, whose real layer probes the filesystem.
// That probe must run once at layer build and expose a resolved value, not
// a live async effect — otherwise runSync throws in the handler. Build the
// real WSL layer (not the sync test stub) and resolve the label with a
// top-level runSync, exactly as the handler does.
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
const runtime = ManagedRuntime.make(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layer),
// isAvailable on win32 only touches the filesystem, never the spawner,
// so a die-stub is enough to satisfy the layer's deps.
Layer.provideMerge(
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.die("spawner should not be used while probing WSL availability"),
),
),
),
Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
Layer.provide(NodeServices.layer),
),
);
try {
const configuration = await runtime.runPromise(
DesktopBackendConfiguration.DesktopBackendConfiguration,
);
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
const label = Effect.runSync(configuration.resolvePrimaryLabel);
assert.equal(typeof label, "string");
} finally {
await runtime.dispose();
}
});
});
@@ -1,3 +1,5 @@
import * as NodeOS from "node:os";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -7,12 +9,16 @@ 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 Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import serverPackageJson from "../../../server/package.json" with { type: "json" };
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
@@ -29,10 +35,31 @@ export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedE
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
readonly resolve: Effect.Effect<
// Build the Windows-native primary backend's start config. Reads the
// primary's port/host/exposure from DesktopServerExposure. Can fail
// with PlatformError because bootstrap token generation now uses
// crypto.randomBytes under the hood (post Effect 4 migration).
readonly resolvePrimary: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// Build a WSL backend start config for the given distro on the given
// port. The WSL backend is always loopback-only (the primary owns LAN
// exposure when the user opts in), so this takes the port directly and
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
// forwarded to wsl.exe with no -d flag.
readonly resolveWsl: (input: {
readonly port: number;
readonly distro: string | null;
}) => Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// The renderer-facing label for the primary instance, derived from the
// same decision resolvePrimary makes (including the WSL-availability
// fall-back to Windows), so the env switcher can't show "WSL" for a
// backend that actually resolved to Windows.
readonly resolvePrimaryLabel: Effect.Effect<string>;
}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
@@ -59,9 +86,48 @@ const DESKTOP_BACKEND_ENV_NAMES = [
"T3CODE_TAILSCALE_SERVE_PORT",
] as const;
// Sensitive env vars that the WSL backend needs but Windows process.env won't
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
// URL-shaped values (colons / slashes) is unreliable.
const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
const getWslEnvEntryName = (entry: string): string => {
const slashIndex = entry.indexOf("/");
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
};
const mergeWslEnv = (
existingWslEnv: string | undefined,
forwardedEnvNames: ReadonlyArray<string>,
): string | undefined => {
const existing = existingWslEnv?.trim() ?? "";
// Names already declared, so we don't forward a duplicate. We parse the
// existing value only for this membership test — the string itself is
// preserved verbatim below rather than re-serialized.
const seenNames = new Set(
existing
.split(":")
.map((entry) => getWslEnvEntryName(entry.trim()))
.filter((name) => name.length > 0),
);
const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
// Preserve the user's WSLENV exactly as Windows handed it to us — empty
// "::" segments and duplicate entries are harmless no-ops to WSL and not
// ours to normalize — and only append the secrets we need to forward
// across the wsl.exe boundary.
const parts = [existing, ...additions].filter((part) => part.length > 0);
return parts.length > 0 ? parts.join(":") : undefined;
};
const logBackendObservabilitySettingsReadFailure = (
settingsPath: string,
cause: PlatformError.PlatformError,
@@ -100,11 +166,168 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
};
});
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}): Effect.fn.Return<
interface SharedBootstrapInput {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}
interface WslPreflightSuccess {
readonly _tag: "Ready";
readonly runningDistro: string;
readonly linuxEntryPath: string;
// Absolute path to the node binary the preflight validated after the shared
// remote resolver repaired PATH. The launch must use this exact path so it
// doesn't fall through to a different/old node than the one node-pty was
// built against.
readonly nodePath: string;
// PATH captured from the same login shell after the shared resolver loaded
// version managers. The launch forwards this value directly without a shell.
readonly resolvedPath: string;
}
interface WslPreflightFailure {
readonly _tag: "Failed";
readonly reason: string;
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
// build tools) and retrying won't help — surface it and (wsl-only) fall back
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
// boots), with a bounded window for self-healing before fallback.
readonly fatal: boolean;
readonly retryLimit?: number;
}
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
readonly distro: string | null;
readonly windowsEntryPath: string;
readonly windowsRepoRoot: string;
readonly allowBuild: boolean;
}): Effect.fn.Return<
WslPreflightSuccess | WslPreflightFailure,
never,
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
> {
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const wslAvailable = yield* wslEnv.isAvailable;
if (!wslAvailable) {
return {
_tag: "Failed",
reason: "WSL is not available on this system",
fatal: false,
} as const;
}
const distroProbe = yield* wslEnv.probeDistros.pipe(
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
);
if (distroProbe._tag === "Failure") {
return {
_tag: "Failed",
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
fatal: false,
} as const;
}
const installedDistros = distroProbe.distros;
const runningDistro = input.distro
? (installedDistros.find(
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
)?.name ?? null)
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
if (runningDistro === null) {
return {
_tag: "Failed",
reason: input.distro
? `WSL distro is not installed: ${input.distro}`
: installedDistros.length === 0
? "WSL has no installed distributions"
: "WSL has no default distribution",
fatal: true,
} as const;
}
const entryExists = yield* fileSystem
.exists(input.windowsEntryPath)
.pipe(Effect.orElseSucceed(() => false));
if (!entryExists) {
return {
_tag: "Failed",
reason: `missing server entry at ${input.windowsEntryPath}`,
fatal: true,
} as const;
}
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
if (Option.isNone(linuxEntry)) {
return {
_tag: "Failed",
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
fatal: false,
} as const;
}
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
allowBuild: input.allowBuild,
nodeEngineRange: serverPackageJson.engines.node,
});
if (!nodePtyResult.ok) {
return {
_tag: "Failed",
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
fatal: nodePtyResult.fatal,
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
} as const;
}
return {
_tag: "Ready",
runningDistro,
linuxEntryPath: linuxEntry.value,
nodePath: nodePtyResult.nodePath,
resolvedPath: nodePtyResult.resolvedPath,
} as const;
});
// True when the given IPv4 belongs to a Windows-side network
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
// host's, which is the signature we use to detect that mode and
// switch the renderer URL to loopback.
const isLocalHostIpv4 = (ip: string): boolean => {
const interfaces = NodeOS.networkInterfaces();
for (const list of Object.values(interfaces)) {
if (!list) continue;
for (const entry of list) {
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
// the Node build Electron ships (41 / Node 22, verified), but some Node
// builds report the numeric 4. Normalize to a string so a future runtime
// bump can't silently break mirrored-mode detection and leave the
// renderer pointed at the distro IP instead of loopback.
const family = String(entry.family);
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
}
}
return false;
};
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
...Option.match(observabilitySettings.otlpTracesUrl, {
onNone: () => ({}),
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
}),
...Option.match(observabilitySettings.otlpMetricsUrl, {
onNone: () => ({}),
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
}),
});
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
function* (
input: SharedBootstrapInput,
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
@@ -113,70 +336,350 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const backendExposure = yield* serverExposure.backendConfig;
const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: backendExposure.port,
t3Home: environment.baseDir,
host: backendExposure.bindHost,
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
...buildObservabilityFragment(input.observabilitySettings),
};
return {
executablePath: process.execPath,
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
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 }),
}),
},
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
extendEnv: true,
bootstrap,
bootstrapDelivery: "fd3",
httpBaseUrl: backendExposure.httpBaseUrl,
captureOutput: true,
};
preflightFailure: Option.none(),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
},
);
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
input: SharedBootstrapInput & {
readonly port: number;
readonly distro: string | null;
},
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
| DesktopEnvironment.DesktopEnvironment
| DesktopWslEnvironment.DesktopWslEnvironment
| FileSystem.FileSystem
> {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
// Windows. wslhost forwarding is unreliable on some Windows hosts:
// the desktop's readiness probe and the renderer's saved-env-style
// fetch both saw "Failed to fetch" when the backend only bound to
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
// WSL IP as the renderer-visible URL avoids that dependency.
// Security-wise this is acceptable for the local-only WSL backend:
// the network it exposes on is the WSL-vEthernet network, not the
// LAN; the primary owns LAN exposure when the user opts in.
const wslBindHost = "0.0.0.0";
const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: input.port,
// Omit t3Home so the Linux backend uses its own home dir instead of
// the Windows-side baseDir (which would be a /mnt/c path and share
// the SQLite file with the primary).
host: wslBindHost,
desktopBootstrapToken: input.bootstrapToken,
// PortSchema rejects 0, so when tailscale serve is disabled we still
// need a valid number in this slot. The backend reads tailscaleServePort
// only when tailscaleServeEnabled is true, so the actual value here is
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
...buildObservabilityFragment(input.observabilitySettings),
};
// In packaged builds environment.appRoot is .../resources/app.asar — an
// archive FILE. The Windows primary reads its entry through
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
// already a real directory, so this is a no-op.
const wslAppRoot = environment.isPackaged
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
: environment.appRoot;
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
const preflight = yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
});
// Every operation after preflight uses the same concrete distro. In
// default-tracking mode this closes the race where the system default
// changes between probing and spawning the backend.
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
const distroForConfig = runningDistro ?? input.distro;
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
// reports a host interface, so use loopback instead; a failed probe also
// falls back to loopback and preserves the previous behavior.
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
const usesSharedNetworkStack = Option.match(distroIp, {
onNone: () => false,
onSome: (ip) => isLocalHostIpv4(ip),
});
const rendererHost = usesSharedNetworkStack
? "127.0.0.1"
: Option.getOrElse(distroIp, () => "127.0.0.1");
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
const forwardedEnv: Record<string, string> = {};
const forwardedEnvNames: string[] = [];
for (const name of WSL_FORWARDED_ENV_NAMES) {
const value = process.env[name];
if (value !== undefined && value.length > 0) {
forwardedEnv[name] = value;
forwardedEnvNames.push(name);
}
}
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
// exports the Windows-side base dir for the primary; if it leaks into
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
// /mnt/c, which means both backends read/write the same database and
// their env-ids collide).
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(process.env)) {
if (key === "T3CODE_HOME") continue;
parentEnvWithoutT3Home[key] = value;
}
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
const baseConfig = {
executablePath: "wsl.exe",
entryPath: wslEntryPath,
cwd: environment.backendCwd,
env: {
...parentEnvWithoutT3Home,
...backendChildEnvPatch(),
...forwardedEnv,
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
},
// env is already a complete process.env minus T3CODE_HOME; pass it
// verbatim instead of letting the spawner re-merge process.env on top.
extendEnv: false,
bootstrap,
bootstrapDelivery: "stdin" as const,
httpBaseUrl,
captureOutput: true,
...(runningDistro !== null ? { runningDistro } : {}),
};
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
// config resolution lands in dev/ instead of userdata/. Inheriting through
// WSLENV is unreliable in practice (URL-shaped values with colons /
// slashes get translated unpredictably depending on flags), and the
// packaged build leaves devServerUrl as None anyway.
const devUrlArgs = Option.match(environment.devServerUrl, {
onNone: () => [] as ReadonlyArray<string>,
onSome: (url) => ["--dev-url", url.href],
});
if (preflight._tag === "Failed") {
const retryLimit =
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
return {
...baseConfig,
args: [...distroArgs, "--", "node", "--version"],
preflightFailure: Option.some({
reason: preflight.reason,
fatal: preflight.fatal,
...(retryLimit === undefined ? {} : { retryLimit }),
}),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
}
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
// user PATH entries captured by the login-shell preflight. Every dynamic
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
// for the bootstrap envelope.
const lastSlash = preflight.nodePath.lastIndexOf("/");
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
return {
...baseConfig,
args: [
...distroArgs,
"--exec",
"env",
`PATH=${launchPath}`,
preflight.nodePath,
preflight.linuxEntryPath,
"--bootstrap-fd",
"0",
...devUrlArgs,
],
preflightFailure: Option.none(),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
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;
}
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
// resolve concurrently; with a plain Ref both could observe None, generate
// distinct tokens, and one would overwrite the other — leaving the two
// backends holding mismatched tokens and breaking the shared-token
// invariant the renderer relies on. modifyEffect serializes the whole
// get-or-create so the first caller wins and the rest reuse its token.
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
Option.match(current, {
onSome: (token) => Effect.succeed([token, current] as const),
onNone: () =>
crypto.randomBytes(24).pipe(
Effect.map((bytes) => {
const token = Encoding.encodeHex(bytes);
return [token, Option.some(token)] as const;
}),
),
}),
);
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
// Both resolvers share the same bootstrap token: the renderer holds a
// single token and uses it against whichever backend it's currently
// talking to. Observability settings get re-read each resolve so a
// hot-swap of the server-settings file is picked up on the next
// restart cycle without having to bounce the desktop process.
const sharedInputs = Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
});
const buildWslPrimaryConfig = Effect.gen(function* () {
// wsl-only mode pipes the WSL backend through the same port the
// Windows primary would normally take. That way the renderer
// still loads from the local-only endpoint advertised by
// DesktopServerExposure, and primary-aware code paths (cookie
// auth, the env switcher's "primary" id) keep working without
// a parallel "secondary" registration.
const backendExposure = yield* serverExposure.backendConfig;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
distro: persistedSettings.wslDistro,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
});
const buildWindowsPrimaryConfig = Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolvePrimaryStartConfig(shared).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
});
// Single source of truth for what the primary actually runs as. Both
// the start-config dispatch and the renderer-facing label derive from
// this, so they can't disagree — e.g. the label reading "WSL" while the
// config silently fell back to Windows because WSL is unavailable.
// Dispatch happens at resolve time so toggling wsl-only between restarts
// is picked up on the next start cycle (the pool's primary instance is
// created once at layer init, but configResolve fires on each restart).
const describePrimary = Effect.gen(function* () {
const persistedSettings = yield* settings.get;
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
// Only honor wsl-only when WSL is actually usable. If the user
// persisted wsl-only but WSL has since become unavailable (wsl.exe
// removed, no distro), fall back to the Windows primary instead of
// looping forever on preflight failures: the Connections backend
// control is hidden while WSL is unavailable, so a stuck WSL primary
// would otherwise leave no in-app way back to Windows.
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
});
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,
resolvePrimary: Effect.gen(function* () {
const { useWsl, wslRequested } = yield* describePrimary;
if (useWsl) {
return yield* buildWslPrimaryConfig;
}
if (wslRequested) {
yield* Effect.logWarning(
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
);
}
return yield* buildWindowsPrimaryConfig;
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
resolvePrimaryLabel: Effect.gen(function* () {
const { useWsl, distro } = yield* describePrimary;
if (!useWsl) {
return environment.platform === "win32" ? "Windows" : "Local environment";
}
return distro ? `WSL (${distro})` : "WSL";
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
resolveWsl: (input) =>
Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
attributes: { port: input.port, distro: input.distro ?? null },
}),
),
});
});
File diff suppressed because it is too large. Load diff
+353 -312
View File
@@ -1,35 +1,63 @@
// Per-instance backend factory. Replaces the legacy singleton
// `DesktopBackendManager` Context.Service: each call to
// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
// its own state Ref, mutex, restart loop, and active child process. The
// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
// methods that operate on that single backend.
//
// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
// backend it wants to run. Today that's the Windows primary; follow-up
// commits add a second call for the WSL instance.
//
// Singleton couplings that the legacy service held inline are now
// parameterized via the spec:
// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
// so each instance can resolve its own start config — the primary wires
// `configuration.resolvePrimary`, the WSL orchestrator wires a
// `configuration.resolveWsl({ port, distro })` closure.
// - onReady / onShutdown drive UI side effects (window auto-open,
// readiness latch) only for instances that want them — the primary's
// spec passes the window's handleBackendReady/handleBackendNotReady,
// other pool instances pass nothing.
// - log writes go through a per-instance writer that the factory
// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
// so each instance lands in its own rotating file.
import * as Brand from "effect/Brand";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
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 * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
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);
// After this many consecutive fatal preflight failures, stop the silent
// restart loop and surface the reason via onPreflightFailed. Transient
// failures may instead provide their own larger retryLimit when they should
// self-heal for a while but must not leave the app connecting forever.
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
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);
@@ -42,145 +70,91 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface BackendProcessContext {
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig {
readonly executablePath: string;
readonly args: ReadonlyArray<string>;
readonly entryPath: string;
readonly cwd: string;
readonly env: Record<string, string | undefined>;
// When true the spawner merges the desktop process.env on top of `env`;
// when false `env` is passed verbatim. WSL mode opts out so a leaking
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
readonly extendEnv: boolean;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
readonly preflightFailure: Option.Option<PreflightFailure>;
// Present for a WSL run after the configured/default distro has been
// resolved to the concrete distro passed to wsl.exe.
readonly runningDistro?: string;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly captureOutput: boolean;
// A preflight failure records whether it is fatal. Transient failures (WSL
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
// self-heal; fatal ones (no node, wrong version, missing build tools) are
// surfaced via onPreflightFailed and stop the restart loop after
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
export interface PreflightFailure {
readonly reason: string;
readonly fatal: boolean;
readonly retryLimit?: number;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
url: Schema.instanceOf(URL),
},
) {
override get message(): string {
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
...backendProcessContextSchema,
entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
...backendProcessContextSchema,
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
}
}
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
"DesktopBackendRestartError",
{
reason: Schema.String,
delayMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
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: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -191,18 +165,60 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
{
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>;
}
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
// Opaque identifier for one backend process inside the pool. Today only
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
// these map 1:1 with environment ids on the frontend; keeping them
// desktop-local for now avoids leaking the contracts dependency.
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
PRIMARY_LOCAL_ENVIRONMENT_ID,
);
// One pooled backend instance. Same lifecycle surface as the legacy
// `DesktopBackendManagerShape`; the id and label give the pool registry
// + UI something to route on.
export interface DesktopBackendInstance {
readonly id: BackendInstanceId;
readonly label: Effect.Effect<string>;
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>;
// Polls desiredRunning + the instance's own ready flag until the
// backend reports ready, or the timeout elapses. Returns true on
// ready, false on timeout. Used by the WSL backend swap to drive its
// rollback path.
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
}
// Spec describing one backend instance to spawn. The configResolve
// effect is awaited each time the instance is (re)started so live
// settings changes are picked up on the next start cycle. onReady and
// onShutdown let the primary instance trigger UI side effects (window
// open, global readiness flag) without coupling the factory to those
// concerns; other instances pass them as undefined.
export interface BackendInstanceSpec {
readonly id: BackendInstanceId;
readonly label: Effect.Effect<string>;
// configResolve can now fail with PlatformError because the
// bootstrap-token closure inside DesktopBackendConfiguration uses
// crypto.randomBytes (Effect 4 beta.73 migration).
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
// Receives the *resolved* httpBaseUrl of the run that just became
// ready. The window service uses this to decide what URL to load
// (the WSL backend reports its distro IP, the Windows backend reports
// 127.0.0.1). Splitting this off from configResolve avoids races
// between "fired onReady" and "currentConfig already advanced".
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
readonly onShutdown?: () => Effect.Effect<void>;
// Fired once when a fatal or bounded preflight failure has exhausted its
// retries. Returns true when the callback changed configuration and the
// manager should resolve once more; false stops the failed instance.
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
}
interface ActiveBackendRun {
readonly id: number;
@@ -217,6 +233,9 @@ interface BackendManagerState {
readonly config: Option.Option<DesktopBackendStartConfig>;
readonly active: Option.Option<ActiveBackendRun>;
readonly restartAttempt: number;
// Consecutive bounded/fatal preflight failures, reset on a clean or
// unbounded-transient preflight. restartAttempt counts all restarts.
readonly preflightFailureAttempt: number;
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
readonly nextRunId: number;
}
@@ -227,6 +246,7 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -259,198 +279,135 @@ const closeRun = (
).pipe(Effect.ignore);
};
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
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)),
);
const waitForHttpReady = (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
return waitForHttpReadyShared({
baseUrl: baseUrl.href,
path: BACKEND_READINESS_PATH,
timeoutMs: Duration.toMillis(timeout),
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
});
};
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(options.timeout),
Effect.mapError(
(cause) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
),
);
});
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(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
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({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, 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 bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
const command = ChildProcess.make(options.executablePath, options.args, {
cwd: options.cwd,
env: options.env,
extendEnv: options.extendEnv,
// 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: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
stdout: options.captureOutput ? "pipe" : "inherit",
stderr: options.captureOutput ? "pipe" : "inherit",
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
// wsl.exe drops additional file descriptors when forwarding to the Linux
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
// (`--bootstrap-fd 0`) instead.
...(options.bootstrapDelivery === "fd3"
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
: {}),
});
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
);
const handle = yield* spawner
.spawn(command)
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
const exitCode = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
);
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
export const make = Effect.gen(function* () {
// Factory for one pooled backend instance. The returned instance owns
// its own state Ref, mutex, restart loop, and active child process;
// nothing is shared between instances created from separate
// makeBackendInstance calls. The instance shuts down automatically when
// the calling scope closes (typically the application scope).
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
spec: BackendInstanceSpec,
): Effect.fn.Return<
DesktopBackendInstance,
never,
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| Scope.Scope
> {
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 backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
const mutex = yield* Semaphore.make(1);
const { logWarning: logInstanceWarning, logError: logInstanceError } =
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
Ref.update(state, withActiveRun(runId, f));
@@ -490,11 +447,16 @@ export const make = Effect.gen(function* () {
return;
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve.pipe(
if (current.ready) {
yield* spec.onShutdown?.() ?? Effect.void;
yield* Ref.update(state, (latest) =>
latest.ready ? { ...latest, ready: false } : latest,
);
}
const config = yield* spec.configResolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error,
logInstanceError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
@@ -506,14 +468,84 @@ export const make = Effect.gen(function* () {
.exists(config.value.entryPath)
.pipe(Effect.orElseSucceed(() => false));
const resetFatalPreflightCounter =
!current.desiredRunning && current.preflightFailureAttempt > 0;
yield* cancelRestart;
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
}));
const preflightFailure = config.value.preflightFailure;
if (Option.isSome(preflightFailure)) {
const { reason, fatal, retryLimit } = preflightFailure.value;
if (!fatal && retryLimit === undefined) {
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
// retrying so the backend self-heals once WSL is ready. Reset a
// prior bounded/fatal streak because this is a different failure.
yield* Ref.update(state, (latest) =>
latest.preflightFailureAttempt === 0
? latest
: { ...latest, preflightFailureAttempt: 0 },
);
yield* scheduleRestart(reason);
return;
}
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
const attempt = yield* Ref.modify(state, (latest) => {
const next = latest.preflightFailureAttempt + 1;
return [next, { ...latest, preflightFailureAttempt: next }] as const;
});
if (attempt > attemptLimit) {
// We already surfaced and asked for the Windows fallback, yet we're
// still resolving the WSL primary — the fallback didn't take (e.g.
// the settings write failed). Stop rather than loop forever.
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
reason,
attempt,
});
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: false,
ready: false,
}));
return;
}
if (attempt === attemptLimit) {
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
// on the primary, shows a dialog and persists Windows mode), then
// schedule one more restart so the next resolve picks up the Windows
// primary and a window can open.
yield* logInstanceError(
"backend preflight failed repeatedly; surfacing and falling back",
{ reason, attempt },
);
const shouldRestart = yield* (
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
);
if (shouldRestart) {
yield* scheduleRestart(reason);
} else {
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: false,
ready: false,
}));
}
return;
}
yield* scheduleRestart(reason);
return;
}
// Clean preflight — reset the fatal counter so a later failure gets a
// fresh allowance.
yield* Ref.update(state, (latest) =>
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
);
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
return;
@@ -534,7 +566,7 @@ export const make = Effect.gen(function* () {
},
]);
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
@@ -586,7 +618,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid.value} ${reason}`,
});
}
yield* Ref.set(desktopState.backendReady, false);
yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -598,7 +630,7 @@ export const make = Effect.gen(function* () {
const program = runBackendProcess({
...config.value,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
@@ -608,7 +640,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
if (activeRun?.id !== runId) {
@@ -628,30 +660,19 @@ export const make = Effect.gen(function* () {
return;
}
yield* Ref.set(desktopState.backendReady, true);
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
cause: error,
}),
),
);
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error,
logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
onFailure: (error) =>
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onFailure: (error) => finalizeRun(error.message),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -664,9 +685,9 @@ export const make = Effect.gen(function* () {
}));
}),
),
).pipe(Effect.withSpan("desktop.backendManager.start"));
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
reason: string,
) {
const scheduled = yield* Ref.modify(state, (latest) => {
@@ -686,8 +707,8 @@ export const make = Effect.gen(function* () {
yield* Option.match(scheduled, {
onNone: () => Effect.void,
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
reason,
delayMs: Duration.toMillis(delay),
});
@@ -706,17 +727,11 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopBackendRestartError({
reason,
delayMs: Duration.toMillis(delay),
cause,
});
return logBackendManagerError(error.message, { error });
}),
Effect.catchCause((cause) =>
logInstanceError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
),
parentScope,
);
@@ -732,7 +747,7 @@ export const make = Effect.gen(function* () {
});
});
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
@@ -750,7 +765,15 @@ export const make = Effect.gen(function* () {
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
yield* Ref.set(desktopState.backendReady, false);
// Ignore failures from spec.onShutdown so a downstream throw
// can't abort the rest of stop(). Ref.modify above already
// flipped state to "no active run / no restart fiber", and the
// physical cleanup (Fiber.interrupt + closeRun) runs after the
// mutex releases. If onShutdown were allowed to propagate, both
// would be skipped and the child process + restart fiber would
// be orphaned while state claimed nothing was running — the
// next start() would then spawn a second backend on top.
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
return result;
}),
);
@@ -765,14 +788,32 @@ export const make = Effect.gen(function* () {
});
});
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
Effect.gen(function* () {
const current = yield* Ref.get(state);
// Return false early if an external `stop()` flipped desiredRunning off
// — no point polling for a backend that is being torn down.
if (!current.desiredRunning) return { done: true, ready: false };
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
}).pipe(
Effect.repeat({
until: (status) => status.done,
schedule: Schedule.spaced(Duration.millis(100)),
}),
Effect.map((status) => status.ready),
Effect.timeoutOption(timeout),
Effect.map(Option.getOrElse(() => false)),
);
yield* Effect.addFinalizer(() => stop());
return DesktopBackendManager.of({
return {
id: spec.id,
label: spec.label,
start,
stop,
currentConfig,
snapshot,
});
waitForReady,
} satisfies DesktopBackendInstance;
});
export const layer = Layer.effect(DesktopBackendManager, make);
@@ -0,0 +1,138 @@
import { assert, describe, it } from "@effect/vitest";
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 Ref from "effect/Ref";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
function makeStubInstance(
id: DesktopBackendPool.BackendInstanceId,
label: string,
): DesktopBackendPool.DesktopBackendInstance {
const snapshot: DesktopBackendSnapshot = {
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
};
return {
id,
label: Effect.succeed(label),
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
snapshot: Effect.succeed(snapshot),
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
};
}
function makePoolLayer(
labelRef: Ref.Ref<string>,
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
return DesktopBackendPool.layer.pipe(
Layer.provideMerge(
Layer.mergeAll(
FileSystem.layerNoop({}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () =>
Effect.succeed({
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolvePrimary: Effect.die("unexpected primary config resolve"),
resolvePrimaryLabel: Ref.get(labelRef),
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
DesktopAppSettings.layerTest(),
ElectronDialog.layer,
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window create"),
ensureMain: Effect.die("unexpected window ensure"),
revealOrCreateMain: Effect.die("unexpected window reveal"),
activate: Effect.die("unexpected window activate"),
createMainIfBackendReady: Effect.die("unexpected window create"),
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
),
);
}
describe("DesktopBackendPool", () => {
it.effect("layerTest exposes registered instances by id", () =>
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
const all = yield* pool.list;
const resolvedPrimary = yield* pool.primary;
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
assert.isTrue(Option.isNone(fetchedMissing));
assert.lengthOf(all, 2);
// First instance becomes primary in layerTest so single-instance
// stubs don't have to wire an explicit primary.
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
}).pipe(
Effect.provide(
DesktopBackendPool.layerTest([
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
]),
),
),
);
it.effect("layerTest dies when no instances are supplied", () =>
Effect.exit(
Effect.gen(function* () {
yield* DesktopBackendPool.DesktopBackendPool;
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
);
it.effect("resolves the primary label lazily after pool layer construction", () =>
Effect.scoped(
Effect.gen(function* () {
const labelRef = yield* Ref.make("Windows");
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
Effect.provide(makePoolLayer(labelRef)),
);
const primary = yield* pool.primary;
yield* Ref.set(labelRef, "WSL (Ubuntu)");
assert.equal(yield* primary.label, "WSL (Ubuntu)");
}),
),
);
});
@@ -0,0 +1,470 @@
// Pool registry for multiple backend processes. This file is the entry
// point for the concurrent-Windows+WSL-backend feature; see the design
// notes below before extending it.
//
// Current state:
// - `DesktopBackendManager.ts` exposes a per-instance factory
// (`makeBackendInstance(spec)`); the pool calls it once for the
// Windows primary at startup, and `DesktopWslBackend.reconcile`
// calls it through `pool.register` to bring up the WSL instance
// when the user enables it.
// - The primary spec wires `configResolve` to
// `DesktopBackendConfiguration.resolvePrimary` and the
// `onReady`/`onShutdown` callbacks to the window service. WSL
// instances wire `configResolve: configuration.resolveWsl(...)`
// and skip onReady/onShutdown — the window only follows the primary.
// - The pool exposes `register(spec)` and `unregister(id)`. Each
// registered instance gets its own child scope, so unregister can
// stop it cleanly without tearing down the pool. The primary's id
// refuses unregister.
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
// load. IPC surface is `setWslBackendEnabled(boolean)` +
// `setWslDistro(string | null)`; both persist and then call the
// orchestrator's reconcile. No swap, no rollback, primary stays up.
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
// pool instance currently registered with bootstrap info. The
// primary keeps the "primary" id; WSL instances are "wsl:default"
// or "wsl:<distro>".
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
// it gives the Windows picker — what every existing caller gets,
// and what non-WSL users see. WSL targets route to the wsl helpers.
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
// picker that shows up when the toggle is on. Default-off, so
// users who never opted in see the same surface as before.
//
// Renderer-side wiring (apps/web/src/environments/local/):
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
// skips the primary (which the existing primary/ runtime owns),
// and for every other entry POSTs the shared bootstrap token to
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
// writes the bearer to the secret store, and opens a connection
// through the same saved-env path remote envs use.
// - The desktopLocal marker filters records out of saved-env
// persistence, so toggling WSL off or switching distros doesn't
// pollute the user's settings file. The sidebar, CommandPalette,
// env switcher, and project-id routing all read the saved-env
// registry, so the WSL backend shows up there without any
// per-surface changes.
//
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
// wslDistro="Ubuntu"):
// - Two backends listening on distinct loopback ports
// (server.log: 13773 primary, 13774 wsl).
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
// - Distinct environment ids reported by each backend's
// /.well-known/t3/environment (Windows vs Linux platform).
// - Renderer completes the bearer-token bootstrap against the WSL
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
// ws-token (POST /api/auth/ws-token 200), and holds an
// ESTABLISHED WebSocket connection to both ports (netstat).
//
// Migration history (commits):
// 1. Reshape `DesktopBackendManager` into an instance factory and route
// consumers through the pool. Pool held a single instance. (a8fc7845)
// 2. Drop `DesktopState.backendReady`. The window owns its own
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
// 4. Add register/unregister to the pool. (a0eaf560)
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
// split, DesktopWslBackend orchestrator, new IPC, web compat.
// (b1622191 + 31ce3add + 627c80cb)
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
// 9. Register WSL backend as desktop-local saved env via
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
// 10. CommandPalette enables file-manager picker for desktop-local
// envs, routes pickFolder by env id. (38e8477a)
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as FileSystem from "effect/FileSystem";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
const { logWarning: logBackendPoolWarning } =
DesktopObservability.makeComponentLogger("desktop-backend-pool");
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
// Caller tried to register an id that's already in the pool. The pool
// refuses overwrites so two independent orchestrators racing on the
// same id surface as a typed failure instead of one silently winning.
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
"DesktopBackendPoolInstanceAlreadyRegisteredError",
{
id: Schema.String,
},
) {
override get message() {
return `Backend instance "${this.id}" is already registered in the pool.`;
}
}
// Primary instance is registered for the pool's lifetime. Unregister is
// a no-op for it today (no real callers), but if someone wires it up
// later it's a clear bug rather than something to "handle".
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
"DesktopBackendPoolCannotUnregisterPrimaryError",
{},
) {
override get message() {
return "Refusing to unregister the primary backend from the pool.";
}
}
export class DesktopBackendPool extends Context.Service<
DesktopBackendPool,
{
// Look up a registered instance. None when no backend with that id is
// currently registered (e.g. WSL backend disabled).
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
// Snapshot of all currently-registered instances. Order is unspecified;
// callers that need a canonical "primary first" view should sort by id.
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
// Convenience accessor for the always-registered primary instance.
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
// exposed as a typed effect so consumers don't have to handle the
// Option for the case that's guaranteed to be present.
readonly primary: Effect.Effect<DesktopBackendInstance>;
// Build a fresh DesktopBackendInstance from `spec` and add it to the
// registry. The pool owns the instance's scope: unregister(id) or pool
// teardown closes it and runs the instance's auto-stop finalizer. The
// returned instance has not been started — callers decide when to
// start it (and can call start more than once if a retry-after-failure
// story makes sense for them).
readonly register: (
spec: BackendInstanceSpec,
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
// Stop the named instance and remove it from the registry. Closing the
// instance's scope triggers its auto-stop finalizer; the registry is
// updated atomically with the scope close so subsequent get(id) calls
// observe the unregister before the underlying child process has fully
// exited.
readonly unregister: (
id: BackendInstanceId,
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
}
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
// Services required by makeBackendInstance — exported so caller
// orchestrators that build their own specs can confirm the layer graph
// satisfies them at compile time.
export type BackendInstanceFactoryRequirements =
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory;
interface ActiveRegisteredInstance {
readonly _tag: "Active";
readonly instance: DesktopBackendInstance;
// None for the primary (which lives in the pool's own layer scope and
// is never unregistered); Some for instances added via register, whose
// scope unregister closes to stop them.
readonly scope: Option.Option<Scope.Closeable>;
}
interface ClosingRegisteredInstance {
readonly _tag: "Closing";
readonly done: Deferred.Deferred<void>;
}
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
type RegisterAction =
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
type UnregisterAction =
| { readonly _tag: "Absent" }
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
export const layer = Layer.effect(
DesktopBackendPool,
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
// Anchor the pool's lifetime to its layer scope so registered
// instance scopes can be forked off it. Without this, instance
// scopes are orphaned: they only close via explicit unregister()
// calls, so on app shutdown the WSL backend child process gets
// hard-killed by the OS instead of receiving the graceful
// SIGTERM + grace period the instance's stop finalizer would
// otherwise run.
const layerScope = yield* Scope.Scope;
// Capture the services needed to build any future instance from the
// pool's layer scope. register() runs `makeBackendInstance` against
// a fresh child scope but reuses these services so the instance gets
// the same FileSystem, spawner, HTTP client and log factory the
// primary instance uses.
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
// A WSL preflight failure on the primary only happens in wsl-only mode.
// Fatal configuration failures persist the Windows fallback. Bounded
// transport failures use an in-memory fallback for this launch so the app
// opens without overwriting the user's WSL preference.
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
function* (failure: DesktopBackendManager.PreflightFailure) {
const { reason, fatal } = failure;
if (!fatal) {
yield* logBackendPoolWarning(
"primary WSL preflight retry window exhausted; using Windows for this launch",
{ reason },
);
yield* electronDialog.showErrorBox(
"WSL backend is still unavailable",
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
);
yield* appSettings.applyWslWindowsFallbackInMemory;
return true;
}
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
reason,
});
yield* electronDialog.showErrorBox(
"WSL backend couldn't start",
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
);
// Fully disable the WSL backend — both flags, matching the "Switch to
// Windows" recovery path — so the manager's next restart re-resolves the
// primary as Windows and reconcile won't register a secondary WSL backend
// against the same broken setup. Clearing wslBackendEnabled alone would
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
// mode the next time they enable WSL. If the persisted write fails, keep
// this process recoverable by applying the fallback to in-memory settings.
yield* appSettings.applyWslWindowsFallback.pipe(
Effect.catch((error) =>
logBackendPoolWarning(
"failed to persist Windows fallback after WSL preflight failure",
{
error: error.message,
},
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
),
);
return true;
},
);
const primary = yield* DesktopBackendManager.makeBackendInstance({
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
// Keep this lazy. The pool layer is initialized before startup loads
// persisted desktop settings, so resolving the primary label here would
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
// primaries as Windows.
label: configuration.resolvePrimaryLabel,
configResolve: configuration.resolvePrimary,
// Window creation errors propagating out of handleBackendReady must
// not block the readiness callback (that would prevent restartAttempt
// from being reset), so we absorb them here. The window service only
// logs on success, so log the failure here before swallowing it —
// otherwise a post-readiness window-open failure vanishes silently and
// is near-impossible to diagnose in production.
onReady: (httpBaseUrl) =>
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
Effect.catch((error) =>
logBackendPoolWarning("failed to open main window after backend readiness", {
error: error.message,
}),
),
),
onShutdown: () => desktopWindow.handleBackendNotReady,
onPreflightFailed: handlePrimaryPreflightFailure,
});
const instancesRef = yield* SynchronizedRef.make<
ReadonlyMap<BackendInstanceId, RegisteredInstance>
>(
new Map([
[
DesktopBackendManager.PRIMARY_INSTANCE_ID,
{ _tag: "Active", instance: primary, scope: Option.none() },
],
]),
);
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
Effect.suspend(() =>
SynchronizedRef.modifyEffect(
instancesRef,
(
current,
): Effect.Effect<
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
DesktopBackendPoolInstanceAlreadyRegisteredError
> => {
const existing = current.get(spec.id);
if (existing?._tag === "Active") {
return Effect.fail(
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
);
}
if (existing?._tag === "Closing") {
return Effect.succeed([
{ _tag: "Wait", done: existing.done } as const,
current,
] as const);
}
return Effect.gen(function* () {
// Provide the captured factory services first, then the child scope
// last so instance finalizers are owned by the unregisterable scope.
const instanceScope = yield* Scope.fork(layerScope, "sequential");
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
Effect.provide(factoryContext),
Scope.provide(instanceScope),
);
const next = new Map(current);
next.set(spec.id, {
_tag: "Active",
instance,
scope: Option.some(instanceScope),
});
return [
{ _tag: "Registered", instance } as const,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const;
});
},
).pipe(
Effect.flatMap((result) =>
result._tag === "Registered"
? Effect.succeed(result.instance)
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
),
),
);
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
Effect.gen(function* () {
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
}
const done = yield* Deferred.make<void>();
const action = yield* SynchronizedRef.modifyEffect(
instancesRef,
(
current,
): Effect.Effect<
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
> => {
const entry = current.get(id);
if (entry === undefined) {
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
}
if (entry._tag === "Closing") {
return Effect.succeed([
{ _tag: "Wait", done: entry.done } as const,
current,
] as const);
}
const next = new Map(current);
next.set(id, { _tag: "Closing", done });
return Effect.succeed([
{ _tag: "Close", entry } as const,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const);
},
);
if (action._tag === "Absent") return;
if (action._tag === "Wait") {
yield* Deferred.await(action.done);
return;
}
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
const closing = current.get(id);
if (closing?._tag !== "Closing" || closing.done !== done) {
return Effect.succeed([undefined, current] as const);
}
const next = new Map(current);
next.delete(id);
return Effect.succeed([
undefined,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const);
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
yield* Option.match(action.entry.scope, {
onNone: () => Effect.void,
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
}).pipe(Effect.ensuring(finish));
});
return DesktopBackendPool.of({
get: (id) =>
SynchronizedRef.get(instancesRef).pipe(
Effect.map((instances) => {
const entry = instances.get(id);
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
}),
),
list: SynchronizedRef.get(instancesRef).pipe(
Effect.map((instances) =>
Array.from(instances.values()).flatMap((entry) =>
entry._tag === "Active" ? [entry.instance] : [],
),
),
),
primary: Effect.succeed(primary),
register,
unregister,
});
}),
);
// Test layer for unit tests that want to assert against a known pool
// composition without standing up the full manager. Each provided
// instance is registered under its own id; the first one is also
// surfaced as `primary` so callers can stub a single-instance pool.
// `register` and `unregister` are stubbed to die so tests that
// accidentally exercise pool registration fail loudly instead of
// silently noop'ing.
export const layerTest = (
instances: readonly DesktopBackendInstance[],
): Layer.Layer<DesktopBackendPool> =>
Layer.effect(
DesktopBackendPool,
Effect.gen(function* () {
if (instances.length === 0) {
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
}
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
instances.map((instance) => [instance.id, instance] as const),
);
const primary = instances[0]!;
return DesktopBackendPool.of({
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
list: Effect.succeed(Array.from(byId.values())),
primary: Effect.succeed(primary),
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
});
}),
);
@@ -5,11 +5,12 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config: DesktopBackendManager.DesktopBackendStartConfig = {
const config = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
@@ -54,20 +55,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
),
),
);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
list: Effect.succeed([
{
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
label: Effect.succeed("Windows"),
currentConfig: Effect.succeed(Option.some(config)),
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
@@ -1,4 +1,5 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -8,7 +9,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
@@ -42,7 +43,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
@@ -55,14 +56,20 @@ export const make = Effect.gen(function* () {
return cached.value;
}
const configOption = yield* backendManager.currentConfig;
const instances = yield* pool.list;
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
const credential = config.bootstrap.desktopBootstrapToken;
if (!credential) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential: config.bootstrap.desktopBootstrapToken,
credential,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
@@ -250,9 +250,15 @@ describe("DesktopServerExposure", () => {
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
return withHarness(
+12 -2
View File
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
({
id: 7,
webContents: { getZoomFactor: () => zoomFactor },
}) as unknown as Electron.BrowserWindow;
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(),
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
});
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => {
it.effect("resolves with none when the menu closes without a click", () =>
Effect.gen(function* () {
let popupOptions: Electron.PopupOptions | undefined;
buildFromTemplateMock.mockImplementation(() => ({
popup: (options: Electron.PopupOptions) => {
popupOptions = options;
options.callback?.();
},
}));
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(2),
items: [{ id: "copy", label: "Copy" }],
position: Option.some({ x: 10.8, y: 20.2 }),
});
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(popupOptions?.x, 21);
assert.equal(popupOptions?.y, 40);
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
label: "Copy",
enabled: true,
+13 -3
View File
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
return normalizedItems;
}
// Renderer positions arrive in CSS pixels; popup() expects window points, so
// page zoom must be factored in or menus drift proportionally to their
// distance from the window origin.
const normalizePosition = (
position: Option.Option<ElectronMenuPosition>,
zoomFactor: number,
): 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) })));
({ x, y }) =>
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
).pipe(
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
);
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () {
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupPosition = normalizePosition(
input.position,
input.window.webContents.getZoomFactor(),
);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+45 -2
View File
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -114,18 +115,60 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers: request.headers,
headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
@@ -46,49 +46,14 @@ describe("ElectronShell", () => {
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("preserves safe URL context and cause when Electron rejects openExternal", () =>
it.effect("returns false when Electron rejects openExternal", () =>
Effect.gen(function* () {
const cause = new Error("open failed");
openExternalMock.mockRejectedValue(cause);
const externalUrl =
"HTTPS://user:[email protected]:443/signed-secret-token/path?access_token=secret#fragment";
openExternalMock.mockRejectedValue(new Error("open failed"));
const electronShell = yield* ElectronShell.ElectronShell;
const error = yield* Effect.flip(electronShell.openExternal(externalUrl));
const result = yield* electronShell.openExternal("https://example.com/path");
assert.instanceOf(error, ElectronShell.ElectronShellOpenExternalError);
assert.isTrue(ElectronShell.isElectronShellError(error));
assert.strictEqual(error.urlHostname, "example.com");
assert.strictEqual(error.urlLength, externalUrl.length);
assert.strictEqual(error.urlProtocol, "https:");
assert.strictEqual(error.cause, cause);
assert.notProperty(error, "externalUrl");
assert.notProperty(error, "requestTarget");
assert.notMatch(
error.message,
/user|password|signed-secret-token|path|access_token|secret|fragment/,
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("preserves non-sensitive clipboard context and cause", () =>
Effect.gen(function* () {
const cause = new Error("clipboard failed");
writeTextMock.mockImplementation(() => {
throw cause;
});
const electronShell = yield* ElectronShell.ElectronShell;
const error = yield* Effect.flip(electronShell.copyText("secret text"));
assert.instanceOf(error, ElectronShell.ElectronShellCopyTextError);
assert.isTrue(ElectronShell.isElectronShellError(error));
assert.strictEqual(error.textLength, 11);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "11 characters");
assert.notInclude(error.message, "secret text");
assert.notInclude(error.message, cause.message);
assert.equal(result, false);
}).pipe(Effect.provide(ElectronShell.layer)),
);
});
+13 -65
View File
@@ -1,47 +1,12 @@
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
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 Schema from "effect/Schema";
import * as Electron from "electron";
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
export class ElectronShellOpenExternalError extends Schema.TaggedErrorClass<ElectronShellOpenExternalError>()(
"ElectronShellOpenExternalError",
{
urlHostname: Schema.String,
urlLength: Schema.Number,
urlProtocol: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to open external URL for ${this.urlHostname} (${this.urlProtocol}, input length ${this.urlLength}).`;
}
}
export class ElectronShellCopyTextError extends Schema.TaggedErrorClass<ElectronShellCopyTextError>()(
"ElectronShellCopyTextError",
{
textLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to copy ${this.textLength} characters to the clipboard.`;
}
}
export const ElectronShellError = Schema.Union([
ElectronShellOpenExternalError,
ElectronShellCopyTextError,
]);
export type ElectronShellError = typeof ElectronShellError.Type;
export const isElectronShellError = Schema.is(ElectronShellError);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
return Option.none();
@@ -55,46 +20,29 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
function describeExternalUrl(externalUrl: string, inputLength: number) {
const diagnostics = getUrlDiagnostics(externalUrl);
return {
urlHostname: diagnostics.hostname ?? "",
urlLength: inputLength,
urlProtocol: diagnostics.protocol ?? "",
};
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (
rawUrl: unknown,
) => Effect.Effect<boolean, ElectronShellOpenExternalError>;
readonly copyText: (text: string) => Effect.Effect<void, ElectronShellCopyTextError>;
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export const make = ElectronShell.of({
openExternal: (rawUrl) => {
const inputLength = typeof rawUrl === "string" ? rawUrl.length : 0;
return Option.match(parseSafeExternalUrl(rawUrl), {
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
onSome: (externalUrl) =>
Effect.tryPromise({
try: () => Electron.shell.openExternal(externalUrl),
catch: (cause) =>
new ElectronShellOpenExternalError({
...describeExternalUrl(externalUrl, inputLength),
cause,
}),
}).pipe(Effect.as(true)),
});
},
Effect.promise(() =>
Electron.shell.openExternal(externalUrl).then(
() => true,
() => false,
),
),
}),
copyText: (text) =>
Effect.try({
try: () => Electron.clipboard.writeText(text),
catch: (cause) => new ElectronShellCopyTextError({ textLength: text.length, cause }),
Effect.sync(() => {
Electron.clipboard.writeText(text);
}),
});
@@ -10,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
autoInstallOnAppQuit: true,
channel: "latest",
disableDifferentialDownload: false,
fullChangelog: false,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve([])),
on: vi.fn(),
@@ -33,6 +34,7 @@ describe("ElectronUpdater", () => {
autoUpdaterMock.autoInstallOnAppQuit = true;
autoUpdaterMock.channel = "latest";
autoUpdaterMock.disableDifferentialDownload = false;
autoUpdaterMock.fullChangelog = false;
autoUpdaterMock.checkForUpdates.mockClear();
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
autoUpdaterMock.downloadUpdate.mockClear();
@@ -98,6 +100,18 @@ describe("ElectronUpdater", () => {
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("sets full changelog mode", () =>
Effect.gen(function* () {
const updater = yield* ElectronUpdater.ElectronUpdater;
yield* updater.setFullChangelog(true);
assert.equal(autoUpdaterMock.fullChangelog, true);
yield* updater.setFullChangelog(false);
assert.equal(autoUpdaterMock.fullChangelog, false);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
@@ -66,6 +66,7 @@ export class ElectronUpdater extends Context.Service<
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
@@ -112,6 +113,11 @@ export const make = ElectronUpdater.of({
autoUpdater.allowDowngrade = value;
return Effect.void;
}),
setFullChangelog: (value) =>
Effect.suspend(() => {
autoUpdater.fullChangelog = value;
return Effect.void;
}),
setDisableDifferentialDownload: (value) =>
Effect.suspend(() => {
autoUpdater.disableDifferentialDownload = value;
+10 -2
View File
@@ -33,21 +33,24 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
getWindowFullscreenState,
openExternal,
pickFolder,
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
@@ -70,6 +73,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTailscaleServeEnabled);
yield* ipc.handle(getAdvertisedEndpoints);
yield* ipc.handle(getWslState);
yield* ipc.handle(setWslBackendEnabled);
yield* ipc.handle(setWslDistro);
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
+8 -1
View File
@@ -4,6 +4,8 @@ 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 GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
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";
@@ -11,7 +13,7 @@ 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_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
@@ -32,6 +34,11 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
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 GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state";
export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
@@ -1,28 +1,16 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshPasswordPromptCancellationError,
} from "@t3tools/contracts";
import { SshHttpBridgeError, SshPasswordPromptError } from "@t3tools/ssh/errors";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import {
DesktopSshEnvironmentRequestError,
ensureSshEnvironment,
fetchSshEnvironmentDescriptor,
} from "./sshEnvironment.ts";
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
DesktopSshEnvironmentEnsureResultSchema,
);
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
@@ -46,44 +34,6 @@ function makeHttpClientLayer(
}
describe("SSH environment IPC", () => {
it.effect("encodes password prompt cancellations with structured context and their cause", () => {
const promptCause = new DesktopSshPasswordPrompts.DesktopSshPromptWindowClosedError({
requestId: "prompt-1",
destination: "[email protected]",
});
const cause = new SshPasswordPromptError({
message: promptCause.message,
cause: promptCause,
});
const layer = Layer.succeed(
DesktopSshEnvironment.DesktopSshEnvironment,
DesktopSshEnvironment.DesktopSshEnvironment.of({
discoverHosts: () => Effect.die("unexpected host discovery"),
ensureEnvironment: () => Effect.fail(cause),
disconnectEnvironment: () => Effect.die("unexpected disconnect"),
}),
);
return Effect.gen(function* () {
const encoded = yield* ensureSshEnvironment.handler({
target: {
alias: "devbox",
hostname: "devbox.example.test",
username: "developer",
port: 22,
},
});
const error = yield* decodeDesktopSshEnvironmentEnsureResult(encoded);
assert.instanceOf(error, DesktopSshPasswordPromptCancellationError);
assert.equal(error.reason, "window-closed");
assert.equal(error.requestId, "prompt-1");
assert.equal(error.destination, "[email protected]");
assert.instanceOf(error.cause, Error);
assert.instanceOf(error.cause.cause, Error);
}).pipe(Effect.provide(layer));
});
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
const layer = makeHttpClientLayer((request) =>
+14 -23
View File
@@ -2,7 +2,7 @@ import {
bootstrapRemoteBearerSession,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
isRemoteEnvironmentAuthUndeclaredStatusError,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
@@ -15,7 +15,7 @@ import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshEnvironmentTargetSchema,
DesktopSshHttpBaseUrlInputSchema,
DesktopSshPasswordPromptCancellationError,
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
EnvironmentInternalError,
@@ -45,13 +45,6 @@ type DesktopSshEnvironmentRequestOperation =
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
const desktopSshPasswordPromptCancellationReasons = {
DesktopSshPromptCancelledError: "user-cancelled",
DesktopSshPromptWindowClosedError: "window-closed",
DesktopSshPromptServiceStoppedError: "service-stopped",
DesktopSshPromptTimedOutError: "timed-out",
} as const;
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
@@ -59,7 +52,10 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
if (
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
cause instanceof SshHttpBridgeError
) {
return cause.status ?? null;
}
if (isEnvironmentRequestInvalidError(cause)) {
@@ -131,19 +127,14 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
}) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
Effect.catchTags({
SshPasswordPromptError: (error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed(
new DesktopSshPasswordPromptCancellationError({
reason: desktopSshPasswordPromptCancellationReasons[error.cause._tag],
requestId: error.cause.requestId,
destination: error.cause.destination,
cause: error,
}),
)
: Effect.fail(error),
}),
Effect.catch((error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed({
type: DesktopSshPasswordPromptCancelledType,
message: error.message,
})
: Effect.fail(error),
),
);
}),
});
+148
View File
@@ -0,0 +1,148 @@
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 * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
entryPath: "/app/bin.mjs",
cwd: "/app",
env: {},
extendEnv: false,
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3774,
host: "0.0.0.0",
desktopBootstrapToken: "bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
bootstrapDelivery: "stdin",
httpBaseUrl: new URL("http://127.0.0.1:3774"),
captureOutput: true,
preflightFailure: Option.none(),
runningDistro: "Ubuntu",
};
const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
id: DesktopBackendManager.BackendInstanceId("wsl:default"),
label: Effect.succeed("WSL (default distro)"),
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(readyWslConfig)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.some(123),
restartAttempt: 0,
restartScheduled: false,
}),
waitForReady: () => Effect.succeed(true),
};
describe("getLocalEnvironmentBootstraps", () => {
it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, [
{
id: "wsl:default",
label: "WSL (Ubuntu)",
runningDistro: "Ubuntu",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
bootstrapToken: "bootstrap-token",
},
]);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
);
it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
...readyWslConfig,
preflightFailure: Option.some({
reason: "WSL probe timed out",
fatal: false,
retryLimit: 12,
}),
};
const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
...defaultWslInstance,
currentConfig: Effect.succeed(Option.some(retryingConfig)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: false,
activePid: Option.none(),
restartAttempt: 2,
restartScheduled: true,
}),
};
return Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, [
{
id: "wsl:default",
label: "WSL (default distro)",
runningDistro: null,
httpBaseUrl: null,
wsBaseUrl: null,
},
]);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
});
it.effect("omits a bounded transient bootstrap after retries stop", () => {
const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
...defaultWslInstance,
currentConfig: Effect.succeed(
Option.some({
...readyWslConfig,
preflightFailure: Option.some({
reason: "WSL probe timed out",
fatal: false,
retryLimit: 12,
}),
}),
),
snapshot: Effect.succeed({
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 12,
restartScheduled: false,
}),
};
return Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, []);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
});
});
describe("getWindowFullscreenState", () => {
it.effect("reads the current native window state", () => {
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
return Effect.gen(function* () {
assert.isTrue(yield* getWindowFullscreenState.handler());
}).pipe(
Effect.provide(
Layer.mock(ElectronWindow.ElectronWindow)({
currentMainOrFirst: Effect.succeed(Option.some(window)),
}),
),
);
});
});
+139 -15
View File
@@ -4,14 +4,19 @@ import {
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopEnvironmentBootstrap,
} 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 DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
@@ -19,6 +24,11 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import {
extractDistroFromUncPath,
resolveWslPickFolderDefaultPath,
wslUncPathToLinuxPath,
} from "../../wsl/wslPathParsing.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
@@ -45,26 +55,89 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getLocalEnvironmentBootstrap = DesktopIpc.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",
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = yield* electronWindow.currentMainOrFirst;
return Option.isSome(window) && window.value.isFullScreen();
}),
});
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const instances = yield* pool.list;
const bootstraps: DesktopEnvironmentBootstrap[] = [];
for (const instance of instances) {
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
const config = yield* instance.currentConfig;
const snapshot = yield* instance.snapshot;
// A secondary backend (e.g. a parallel WSL backend) that hasn't produced
// a config yet (mid-registration, before its first start cycle) or that
// is retrying a *transient* preflight failure (WSL VM still booting, a
// not-yet-built linux server entry) is not listening on a port. We
// surface it as a *pending* bootstrap (null endpoints, no token) so the
// renderer can show a "Connecting…" indicator while it retries — null
// endpoints keep the renderer from dialing the dead port, avoiding the
// needless /api/auth/bootstrap/bearer error cycles a real endpoint would
// trigger.
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
// Skip the primary (same-origin, no "connecting" affordance) and skip a
// secondary whose preflight failed *fatally* (no node, wrong version,
// missing build tools): it has stopped retrying, so an indefinite
// "Connecting…" would be misleading — its error is surfaced by the
// WSL-state UI instead.
const fatalPreflight =
Option.isSome(config) &&
Option.isSome(config.value.preflightFailure) &&
config.value.preflightFailure.value.fatal;
const stoppedPreflight =
Option.isSome(config) &&
Option.isSome(config.value.preflightFailure) &&
(!snapshot.desiredRunning || !snapshot.restartScheduled);
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
bootstraps.push({
id: instance.id,
label: yield* instance.label,
runningDistro: null,
httpBaseUrl: null,
wsBaseUrl: null,
});
continue;
}
const { bootstrap, httpBaseUrl } = config.value;
const runningDistro = config.value.runningDistro ?? null;
bootstraps.push({
id: instance.id,
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
runningDistro,
httpBaseUrl: httpBaseUrl.href,
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
...(bootstrap.desktopBootstrapToken
? { bootstrapToken: bootstrap.desktopBootstrapToken }
: {}),
}),
});
});
}
return bootstraps;
}),
});
// Pull the distro selection out of a backend instance id like
// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
// for "track the user's WSL default distro" and maps to the
// wslEnv-derived default at picker time.
function extractWslDistroFromEnvironmentId(envId: string): string | null {
if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
return null;
}
const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
return suffix === "default" || suffix.length === 0 ? null : suffix;
}
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
@@ -83,11 +156,62 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
// Three picker modes:
// - targetEnvironmentId omitted: default to the primary picker. Keeps
// the historical behavior unchanged for users who never enabled the
// WSL backend, and is what unfamiliar callers should get out of the
// box.
// - targetEnvironmentId starts with "wsl:": route to the WSL picker
// using the distro encoded in the id (or the user's selected
// wslDistro when the id is the "wsl:default" sentinel).
// - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
const targetId = options?.targetEnvironmentId;
const wslDistroFromTarget =
targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
? extractWslDistroFromEnvironmentId(targetId)
: null;
const useWsl =
targetId !== undefined &&
targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
const settings = yield* appSettings.get;
// Fall back to the persisted wslDistro when the id is the
// "wsl:default" sentinel; the orchestrator uses the same fallback
// for the actual backend.
const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
const defaultPath = useWsl
? Option.fromNullishOr(
resolveWslPickFolderDefaultPath(
options,
{ distro: wslDistro },
yield* wslEnvironment.listDistros,
Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
),
)
: environment.resolvePickFolderDefaultPath(options);
const selectedPath = yield* dialog.pickFolder({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: environment.resolvePickFolderDefaultPath(options),
defaultPath,
});
return Option.getOrNull(selectedPath);
if (Option.isNone(selectedPath)) {
return null;
}
if (!useWsl) {
return selectedPath.value;
}
const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
if (linuxUncPath !== null) {
return linuxUncPath;
}
const converted = yield* wslEnvironment.windowsToWslPath(
extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
selectedPath.value,
);
return Option.getOrElse(converted, () => selectedPath.value);
}),
});
+274
View File
@@ -0,0 +1,274 @@
import { DesktopWslStateSchema } from "@t3tools/contracts";
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 Schema from "effect/Schema";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
import * as DesktopState from "../../app/DesktopState.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWindow from "../../window/DesktopWindow.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
const invokeSetWslBackendEnabled = (enabled: boolean) =>
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslDistro = (distro: string | null) =>
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslOnly = (enabled: boolean) =>
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
return Layer.succeed(
DesktopWslBackend.DesktopWslBackend,
DesktopWslBackend.DesktopWslBackend.of({
reconcile: input.onReconcile ?? Effect.void,
lastPreflightError: Effect.succeed(Option.none()),
}),
);
}
function makeLifecycleLayer(relaunchReasons: Array<string>) {
return Layer.succeed(
DesktopLifecycle.DesktopLifecycle,
DesktopLifecycle.DesktopLifecycle.of({
relaunch: (reason) =>
Effect.sync(() => {
relaunchReasons.push(reason);
}),
register: Effect.void,
}),
);
}
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
DesktopShutdown.layer,
DesktopState.layer,
Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of(
{} as DesktopEnvironment.DesktopEnvironment["Service"],
),
),
Layer.succeed(
DesktopWindow.DesktopWindow,
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
),
Layer.succeed(
ElectronApp.ElectronApp,
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
),
Layer.succeed(
ElectronTheme.ElectronTheme,
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
),
);
describe("WSL IPC", () => {
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
yield* invokeSetWslOnly(false);
yield* invokeSetWslDistro("Debian");
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const stagedMode = yield* invokeSetWslOnly(true);
assert.equal(stagedMode.enabled, false);
assert.equal(stagedMode.wslOnly, true);
assert.deepEqual(relaunchReasons, []);
yield* invokeSetWslDistro("Debian");
assert.deepEqual(relaunchReasons, []);
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: null,
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("reconciles in dual-backend mode without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.equal(state.enabled, true);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const settings = yield* appSettings.get;
assert.deepEqual(state, {
enabled: false,
distro: null,
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.equal(settings.wslBackendEnabled, false);
assert.equal(settings.wslOnly, false);
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
}).pipe(Effect.provide(layer));
});
it.effect("clears dual-backend WSL without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
assert.equal(state.enabled, false);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
});
+122
View File
@@ -0,0 +1,122 @@
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const readWslState: Effect.Effect<
DesktopWslState,
never,
| DesktopAppSettings.DesktopAppSettings
| DesktopWslEnvironment.DesktopWslEnvironment
| DesktopWslBackend.DesktopWslBackend
> = Effect.gen(function* () {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const settings = yield* appSettings.get;
const available = yield* wslEnvironment.isAvailable;
// Only enumerate distros when WSL is actually available — listDistros on a
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
const distros = available ? yield* wslEnvironment.listDistros : [];
const preflightError = yield* wslBackend.lastPreflightError;
return {
enabled: settings.wslBackendEnabled,
distro: settings.wslDistro,
available,
wslOnly: settings.wslOnly,
distros,
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
// a dialog + Windows fallback, so it stays null there.
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
};
});
export const getWslState = makeIpcMethod({
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
return yield* readWslState;
}),
});
export const setWslBackendEnabled = makeIpcMethod({
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const previousSettings = yield* appSettings.get;
const updateSettings = enabled
? appSettings.setWslBackendEnabled(true)
: appSettings.applyWslWindowsFallback;
const change = yield* updateSettings;
const settings = yield* appSettings.get;
const changedWslOnlyPrimary = enabled
? settings.wslOnly
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
if (changedWslOnlyPrimary && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
return state;
}
// Reconcile is idempotent and never fails; no need for a swap-style
// rollback when the WSL side has trouble coming up. With both
// backends running side by side, "WSL didn't start" is a transient
// state on one instance — the primary stays up either way.
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslDistro = makeIpcMethod({
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
payload: Schema.NullOr(Schema.String),
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslDistro(distro);
const settings = yield* appSettings.get;
// In active wsl-only mode the pool's primary IS the WSL backend, and its
// distro is captured when that backend starts, so relaunch to replace it.
// When WSL is disabled, this only stages a preference for the next enable.
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
return state;
}
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslOnly = makeIpcMethod({
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
// wsl-only decides which backend the pool spins up as "primary", and that
// decision is captured once at layer init. A disabled WSL backend always
// leaves Windows primary active, so mode changes can be staged without a
// relaunch and applied by the subsequent enable call.
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslOnly(enabled);
const state = yield* readWslState;
if (state.enabled && change.changed) {
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
}
return state;
}),
});
+18 -2
View File
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
@@ -50,6 +50,8 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
const desktopEnvironmentLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -143,12 +145,25 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopPreviewLayer),
);
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
// Pool layer instantiates the backend factory once for the Windows
// primary instance and exposes it via pool.primary. Consumers go through
// the pool now; the legacy DesktopBackendManager service is gone. The
// WSL second instance gets registered later in the migration. See
// DesktopBackendPool.ts header for the full rollout plan.
const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(desktopWindowLayer),
);
// WSL orchestrator hangs off the backend layer because it needs the
// pool + configuration + serverExposure; it pulls NetService and the
// foundation services through the same provideMerge chain.
const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
@@ -160,6 +175,7 @@ const desktopApplicationLayer = Layer.mergeAll(
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
+35 -20
View File
@@ -1,31 +1,28 @@
import {
DesktopSshPasswordPromptCancellationError,
DesktopSshPasswordPromptCancellationErrorTag,
type DesktopBridge,
type DesktopPreviewPointerEvent,
type DesktopPreviewRecordingFrame,
type DesktopPreviewTabState,
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as Schema from "effect/Schema";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
const decodeDesktopSshPasswordPromptCancellationError = Schema.decodeUnknownSync(
DesktopSshPasswordPromptCancellationError,
);
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
result !== null &&
"_tag" in result &&
result._tag === DesktopSshPasswordPromptCancellationErrorTag
"type" in result &&
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
) {
throw decodeDesktopSshPasswordPromptCancellationError(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"]>>;
}
@@ -38,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
getLocalEnvironmentBootstraps: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
if (!Array.isArray(result)) {
return [];
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
@@ -94,6 +91,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL),
setWslBackendEnabled: (enabled) =>
ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
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),
@@ -114,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
getWindowFullscreenState: () =>
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
onWindowFullscreenStateChange: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
if (typeof fullscreen !== "boolean") return;
listener(fullscreen);
};
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
setUpdateChannel: (channel) =>
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
@@ -15,6 +15,7 @@ const { fromPartition, sessions } = vi.hoisted(() => ({
readonly clearStorageData: ReturnType<typeof vi.fn>;
readonly getUserAgent: ReturnType<typeof vi.fn>;
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
readonly setUserAgent: ReturnType<typeof vi.fn>;
}
>(),
@@ -40,6 +41,7 @@ describe("BrowserSession", () => {
clearStorageData: vi.fn(() => Promise.resolve()),
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
setPermissionRequestHandler: vi.fn(),
setPermissionCheckHandler: vi.fn(),
setUserAgent: vi.fn(),
};
sessions.set(partition, browserSession);
@@ -61,6 +63,55 @@ describe("BrowserSession", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("scope-a");
yield* browserSessions.getSession("scope-a");
const browserSession = sessions.get(partition);
assert.isDefined(browserSession);
const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
assert.isFunction(requestHandler);
assert.isFunction(checkHandler);
const requestAllows = (permission: string): boolean => {
let granted: boolean | undefined;
requestHandler(null, permission, (value: boolean) => {
granted = value;
});
assert.isDefined(granted);
return granted;
};
for (const permission of [
"clipboard-read",
"clipboard-sanitized-write",
"notifications",
"geolocation",
]) {
assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
assert.isTrue(
checkHandler(null, permission) as boolean,
`check handler should allow ${permission}`,
);
}
// `clipboard-write` is not a real Electron permission — the async write API
// uses `clipboard-sanitized-write` — so the stale name must not be granted,
// and unrelated permissions stay denied.
for (const permission of ["clipboard-write", "midi"]) {
assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
assert.isFalse(
checkHandler(null, permission) as boolean,
`check handler should deny ${permission}`,
);
}
}).pipe(Effect.provide(layer)),
);
it.effect("preserves partition scope and the platform failure chain", () => {
const nativeCause = new Error("native digest failed");
const platformCause = PlatformError.systemError({
+18 -2
View File
@@ -11,6 +11,20 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
// Permissions granted to preview web content. `clipboard-sanitized-write` is the
// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
// `clipboard-write`, which is not a valid Electron permission name. Async
// clipboard writes are gated by the permission *check* handler (not only the
// request handler), so both handlers must allow it; otherwise built-in "Copy"
// buttons — e.g. the Next.js / Vercel error overlay — fail with
// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-read",
"clipboard-sanitized-write",
"notifications",
"geolocation",
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
"BrowserSessionPartitionDerivationError",
{
@@ -120,9 +134,11 @@ export const make = Effect.gen(function* BrowserSessionMake() {
.replace(/\s*t3code\/[\d.]+/, "");
browserSession.setUserAgent(userAgent);
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
callback(allowed.includes(permission));
callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
});
browserSession.setPermissionCheckHandler((_webContents, permission) =>
ALLOWED_PREVIEW_PERMISSIONS.has(permission),
);
const next = new Map(sessions);
next.set(partition, browserSession);
return [browserSession, next] as const;
+387 -10
View File
@@ -1,4 +1,5 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -18,16 +19,25 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
const {
createFromPath,
fromId,
getFocusedWebContents,
mkdir,
showItemInFolder,
webviewSend,
writeFile,
writeImage,
} = vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
@@ -44,6 +54,7 @@ vi.mock("electron", () => ({
},
webContents: {
fromId,
getFocusedWebContents,
},
}));
@@ -81,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
@@ -97,6 +109,8 @@ const withManager = <A>(
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
@@ -250,6 +264,197 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -511,6 +716,178 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
+236 -74
View File
@@ -25,6 +25,7 @@ import type {
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import {
type BrowserWindow,
@@ -62,6 +63,7 @@ import {
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -378,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
artifactDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
@@ -854,11 +857,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
commandParams?: Record<string, unknown>,
) => Effect.Effect<unknown, PreviewManagerError>;
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
send: SendCommand,
enableRuntime: boolean,
) {
yield* Effect.all(
[
...(enableRuntime ? [send("Runtime.enable")] : []),
send("Input.setIgnoreInputEvents", { ignore: false }),
],
{ concurrency: 2, discard: true },
);
});
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
tabId: string,
wc: Electron.WebContents,
action: string,
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
) {
const sequence = yield* nextCounter(actionSequenceRef);
const startedAt = yield* currentIso;
@@ -899,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return result;
},
);
return yield* use(send);
// Cleanup commands must still run after human input invalidates the action's
// control epoch. Otherwise a partially dispatched input can leave Chromium
// with a held key or focus emulation enabled for subsequent actions.
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
function* (method, commandParams) {
return yield* attemptPromise(
{
operation: `${action}.cleanup.${method}`,
tabId,
webContentsId: wc.id,
},
() => wc.debugger.sendCommand(method, commandParams),
);
},
);
return yield* use(send, sendCleanup);
});
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
exit: Exit.Exit<A, PreviewManagerError>,
@@ -1091,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
) {
if (wc.isDestroyed()) return;
yield* update(tabId, {
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
const zoomFactor = yield* attempt(
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
() => wc.getZoomFactor(),
).pipe(Effect.option);
const computedNavStatus = computeNavStatus(wc);
const canGoBack = wc.navigationHistory.canGoBack();
const canGoForward = wc.navigationHistory.canGoForward();
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
const navStatus =
preserveLoadFailure &&
current.navStatus.kind === "LoadFailed" &&
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const state: PreviewTabState = {
...current,
navStatus,
canGoBack,
canGoForward,
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
});
const sync = () => runFork(syncState());
const failed = (_event: Event, code: number, description: string): void => {
if (code === -3) return;
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const failed = (
_event: Event,
code: number,
description: string,
validatedUrl: string,
isMainFrame: boolean,
): void => {
if (code === -3 || !isMainFrame) return;
runFork(
update(tabId, {
navStatus: {
kind: "LoadFailed",
url: wc.getURL(),
url: validatedUrl || wc.getURL(),
title: wc.getTitle(),
code,
description,
@@ -1161,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
wc.off("did-navigate", sync);
wc.off("did-navigate-in-page", sync);
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("page-title-updated", sync);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
@@ -1173,8 +1244,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-navigate", sync);
wc.on("did-navigate-in-page", sync);
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("page-title-updated", sync);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
@@ -1280,21 +1351,40 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
return;
}
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
if (replacedWebContentsId !== null) {
yield* Effect.all(
[
detachControlSession(tab.webContentsId),
detachListeners(tab.webContentsId),
detachControlSession(replacedWebContentsId),
detachListeners(replacedWebContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
}
const zoomFactor =
replacedWebContentsId !== null
? yield* attempt(
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
() => {
wc.setZoomFactor(tab.zoomFactor);
return tab.zoomFactor;
},
)
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
wc.getZoomFactor(),
);
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
@@ -1313,6 +1403,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor,
updatedAt: registeredAt,
};
return [
@@ -1330,11 +1421,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
@@ -1946,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationClickInput,
send: SendCommand,
) {
yield* Effect.all(
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
{ concurrency: 2, discard: true },
);
yield* prepareAutomationInput(send, true);
const point = yield* resolveClickPoint(tabId, send, input);
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
tabId,
@@ -2011,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
tabId: string,
send: SendCommand,
input: PreviewAutomationTypeInput,
@@ -2021,8 +2104,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const locatorJson = locator
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
: null;
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
const result = yield* evaluateWithDebugger<
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
| { ok: true }
| { invalidSelector: true; message: string }
| { notEditable: true }
| { notFound: true }
>(
tabId,
send,
@@ -2030,12 +2120,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try {
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
if (!element) return { notFound: true };
const textControl =
element instanceof HTMLTextAreaElement ||
(element instanceof HTMLInputElement &&
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
const editable = textControl || element.isContentEditable;
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
element.focus();
if (${input.clear ?? false}) {
if ("value" in element) element.value = "";
else if (element.isContentEditable) element.textContent = "";
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
if (document.activeElement !== element) return { notEditable: true };
const clear = ${input.clear ?? false};
if (clear) {
if (textControl) {
element.select();
} else {
const range = document.createRange();
range.selectNodeContents(element);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
}
const text = ${textJson};
let inserted = true;
if (text.length > 0) {
inserted = document.execCommand("insertText", false, text);
} else if (clear) {
document.execCommand("delete", false);
const cleared = textControl
? element.value.length === 0
: (element.textContent ?? "").length === 0;
if (!cleared) {
if (textControl) {
const prototype = element instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
if (valueSetter) valueSetter.call(element, "");
else element.value = "";
} else {
element.replaceChildren();
}
element.dispatchEvent(new InputEvent("input", {
bubbles: true,
inputType: "deleteContentBackward",
}));
}
}
if (!inserted) return { notEditable: true };
element.dispatchEvent(new Event("change", { bubbles: true }));
return { ok: true };
} catch (error) {
return { invalidSelector: true, message: String(error) };
@@ -2059,6 +2191,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
...automationSelectorDiagnostics(input),
});
}
if ("notEditable" in result) {
return yield* new PreviewAutomationTargetNotEditableError({
tabId,
...automationSelectorDiagnostics(input),
});
}
});
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
@@ -2066,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationTypeInput,
send: SendCommand,
) {
yield* send("Runtime.enable");
yield* focusAutomationTarget(tabId, send, input);
yield* send("Input.insertText", { text: input.text });
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
yield* evaluateWithDebugger(
tabId,
send,
`(() => {
const element = document.activeElement;
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
element?.dispatchEvent(new Event("change", { bubbles: true }));
})()`,
false,
);
// CDP Input.insertText silently drops text until Electron has activated a hidden
// guest WebContents with a pointer event. Editing in the page runtime keeps
// background automation deterministic without stealing foreground app focus.
yield* typeIntoAutomationTarget(tabId, send, input);
});
const automationType = Effect.fn("PreviewManager.automationType")(function* (
@@ -2097,32 +2222,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
tabId: string,
wc: Electron.WebContents,
input: PreviewAutomationPressInput,
send: SendCommand,
sendCleanup: SendCommand,
) {
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
yield* prepareAutomationInput(send, false);
const keySequence = makePreviewAutomationKeySequence(input, {
isMac: hostPlatform === "darwin",
});
const previouslyFocused = yield* attempt(
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
() => webContents.getFocusedWebContents(),
);
let keyDownAttempted = false;
const releaseInput = Effect.gen(function* () {
if (keyDownAttempted) {
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
}
}, 0);
const key = input.key;
const text = key.length === 1 ? key : undefined;
const params = {
key,
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
};
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
Effect.ignore,
);
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
yield* attempt(
{
operation: "automationPress.restoreFocusedWebContents",
tabId,
webContentsId: previouslyFocused.id,
},
() => previouslyFocused.focus(),
).pipe(Effect.ignore);
}
});
// Focus the guest WebContents itself, not its containing BrowserWindow. This
// activates native keyboard behavior for hidden/background previews without
// changing which thread is mounted in the UI. Restore the previous renderer
// after dispatch so automation never leaves the app's input focus behind.
yield* Effect.gen(function* () {
yield* attempt(
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
() => wc.focus(),
);
yield* send("Page.bringToFront");
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
yield* expectAgentInput(tabId, keySequence.signal);
keyDownAttempted = true;
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
}).pipe(Effect.ensuring(releaseInput));
});
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
@@ -2130,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationPressInput,
) {
const wc = yield* requireWebContents(tabId);
yield* withControlSession(tabId, wc, "press", (send) =>
performAutomationPress(tabId, input, send),
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
performAutomationPress(tabId, wc, input, send, sendCleanup),
);
});
@@ -2529,6 +2676,20 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
}
}
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
"PreviewAutomationTargetNotEditableError",
{
tabId: Schema.String,
selectorKind: PreviewAutomationSelectorKind,
selectorLength: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
}
}
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
"PreviewAutomationCoordinatesOutsideViewportError",
{
@@ -2631,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
PreviewAutomationDebuggerAttachedError,
PreviewAutomationEvaluationError,
PreviewAutomationTargetNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationCoordinatesOutsideViewportError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationResultTooLargeError,
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
+203
View File
@@ -0,0 +1,203 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
@@ -11,11 +11,26 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
mainWindowBounds: Schema.optionalKey(
Schema.NullOr(
Schema.Struct({
x: Schema.Number,
y: Schema.Number,
width: Schema.Number,
height: Schema.Number,
}),
),
),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
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),
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
wslOnly: Schema.optionalKey(Schema.Boolean),
});
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
@@ -87,11 +102,16 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings,
);
});
@@ -109,11 +129,16 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
const exposure = yield* settings.setServerExposureMode("local-only");
@@ -205,20 +230,44 @@ describe("DesktopSettings", () => {
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
"mainWindowBounds": { "x": 120, "y": 80, "width": 1280, "height": 900 },
}\n`,
);
assert.deepEqual(yield* settings.load, {
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("rejects window bounds that do not satisfy the domain schema", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
mainWindowMaximized: true,
serverExposureMode: "network-accessible",
});
const loaded = yield* settings.load;
assert.isNull(loaded.mainWindowBounds);
assert.isFalse(loaded.mainWindowMaximized);
assert.equal(loaded.serverExposureMode, "network-accessible");
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -226,12 +275,15 @@ describe("DesktopSettings", () => {
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
yield* settings.setServerExposureMode("network-accessible");
const persisted = yield* decodeDesktopSettingsPatch(
yield* fileSystem.readFileString(environment.desktopSettingsPath),
);
assert.deepEqual(persisted, {
mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
mainWindowMaximized: true,
serverExposureMode: "network-accessible",
} satisfies typeof DesktopSettingsPatch.Type);
}),
@@ -248,11 +300,16 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -270,11 +327,16 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -291,13 +353,108 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const enable = yield* settings.setWslBackendEnabled(true);
assert.isTrue(enable.changed);
assert.equal(enable.settings.wslBackendEnabled, true);
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
assert.isTrue(distro.changed);
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
const reloaded = yield* settings.load;
assert.equal(reloaded.wslBackendEnabled, true);
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
const reject = yield* settings.setWslDistro("bad name!");
assert.equal(reject.settings.wslDistro, null);
const noop = yield* settings.setWslDistro(null);
assert.isFalse(noop.changed);
}),
),
);
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.setWslBackendEnabled(true);
yield* settings.setWslOnly(true);
const persistedFallback = yield* settings.applyWslWindowsFallback;
assert.isTrue(persistedFallback.changed);
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
assert.equal(persistedFallback.settings.wslOnly, false);
const persistedReload = yield* settings.load;
assert.equal(persistedReload.wslBackendEnabled, false);
assert.equal(persistedReload.wslOnly, false);
yield* settings.setWslBackendEnabled(true);
yield* settings.setWslOnly(true);
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
assert.isTrue(volatileFallback.changed);
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
assert.equal(volatileFallback.settings.wslOnly, false);
const current = yield* settings.get;
assert.equal(current.wslBackendEnabled, false);
assert.equal(current.wslOnly, false);
const diskReload = yield* settings.load;
assert.equal(diskReload.wslBackendEnabled, true);
assert.equal(diskReload.wslOnly, true);
}),
),
);
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
wslMode: "wsl",
wslDistro: "Ubuntu-22.04",
});
const loaded = yield* settings.load;
assert.equal(loaded.wslBackendEnabled, true);
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
}),
),
);
it.effect("drops invalid persisted wsl distro values on load", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
wslBackendEnabled: true,
wslDistro: "bad/name",
});
const loaded = yield* settings.load;
assert.equal(loaded.wslBackendEnabled, true);
assert.equal(loaded.wslDistro, null);
}),
),
);
});
@@ -17,13 +17,31 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly mainWindowBounds: DesktopWindowBounds | null;
readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
// Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
// integration. We now run Windows and WSL backends side by side, so the
// setting is just whether the WSL backend should be running alongside the
// primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
// value are migrated to `wslBackendEnabled: true` on load.
readonly wslBackendEnabled: boolean;
readonly wslDistro: string | null;
// When true (and wslBackendEnabled is also true) the desktop runs only
// the WSL backend as the primary, and the Windows-side Node backend is
// not started. Designed for users who develop entirely inside WSL and
// don't want a second backend process running. Defaults to false so
// existing setups stay on the parallel-backends behavior. Changing
// this requires a desktop restart because the pool's primary spec is
// chosen once at layer init.
readonly wslOnly: boolean;
}
export interface DesktopSettingsChange {
@@ -32,21 +50,57 @@ export interface DesktopSettingsChange {
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const MIN_MAIN_WINDOW_SIZE = {
width: 840,
height: 620,
} as const;
export const DesktopWindowBoundsSchema = Schema.Struct({
x: Schema.Int,
y: Schema.Int,
width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.width)),
height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.height)),
});
export type DesktopWindowBounds = typeof DesktopWindowBoundsSchema.Type;
export const DEFAULT_MAIN_WINDOW_SIZE = {
width: 1100,
height: 780,
} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslDistro: null,
wslOnly: false,
};
const DesktopWindowBoundsDocument = Schema.Struct({
x: Schema.Number,
y: Schema.Number,
width: Schema.Number,
height: Schema.Number,
});
const DesktopSettingsDocument = Schema.Struct({
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
// Newer form of the WSL toggle. `wslMode` is still accepted on load so
// existing on-disk settings keep working; on the next persist we write the
// new boolean and the legacy key drops out.
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
wslOnly: Schema.optionalKey(Schema.Boolean),
});
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
@@ -55,6 +109,8 @@ 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 decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema);
const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema);
const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
settings,
@@ -88,6 +144,10 @@ export class DesktopAppSettings extends Context.Service<
{
readonly load: Effect.Effect<DesktopSettings>;
readonly get: Effect.Effect<DesktopSettings>;
readonly setMainWindowBounds: (
bounds: DesktopWindowBounds,
isMaximized: boolean,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setServerExposureMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
@@ -98,6 +158,20 @@ export class DesktopAppSettings extends Context.Service<
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslBackendEnabled: (
enabled: boolean,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslDistro: (
distro: string | null,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslOnly: (
enabled: boolean,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly applyWslWindowsFallback: Effect.Effect<
DesktopSettingsChange,
DesktopSettingsWriteError
>;
readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
}
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
@@ -114,18 +188,36 @@ function normalizeTailscaleServePort(value: unknown): number {
: DEFAULT_TAILSCALE_SERVE_PORT;
}
function normalizeWslDistro(value: unknown): string | null {
return typeof value === "string" && isValidDistroName(value) ? value : null;
}
export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | null {
return Option.getOrNull(decodeDesktopWindowBounds(value));
}
function normalizeDesktopSettingsDocument(
parsed: DesktopSettingsDocument,
appVersion: string,
): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds);
const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
// Newer form wins when both are present; otherwise fall back to the legacy
// `wslMode === "wsl"` signal so users coming off the swap-mode build keep
// their WSL backend enabled.
const wslBackendEnabled =
parsed.wslBackendEnabled === true ||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
@@ -134,6 +226,9 @@ function normalizeDesktopSettingsDocument(
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
wslBackendEnabled,
wslDistro: normalizeWslDistro(parsed.wslDistro),
wslOnly: parsed.wslOnly === true,
};
}
@@ -143,6 +238,12 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
if (settings.mainWindowMaximized) {
document.mainWindowMaximized = true;
}
if (settings.serverExposureMode !== defaults.serverExposureMode) {
document.serverExposureMode = settings.serverExposureMode;
}
@@ -158,6 +259,15 @@ function toDesktopSettingsDocument(
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
}
if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
document.wslBackendEnabled = settings.wslBackendEnabled;
}
if (settings.wslDistro !== defaults.wslDistro) {
document.wslDistro = settings.wslDistro;
}
if (settings.wslOnly !== defaults.wslOnly) {
document.wslOnly = settings.wslOnly;
}
return document;
}
@@ -174,6 +284,22 @@ function setServerExposureMode(
};
}
function setMainWindowBounds(
settings: DesktopSettings,
bounds: DesktopWindowBounds,
isMaximized: boolean,
): DesktopSettings {
return settings.mainWindowBounds !== null &&
desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) &&
settings.mainWindowMaximized === isMaximized
? settings
: {
...settings,
mainWindowBounds: bounds,
mainWindowMaximized: isMaximized,
};
}
function setTailscaleServe(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port: Option.Option<number> },
@@ -204,6 +330,38 @@ function setUpdateChannel(
};
}
function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
return settings.wslBackendEnabled === enabled
? settings
: {
...settings,
wslBackendEnabled: enabled,
};
}
function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
const normalized = normalizeWslDistro(distro);
return settings.wslDistro === normalized
? settings
: {
...settings,
wslDistro: normalized,
};
}
function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
return settings.wslOnly === enabled
? settings
: {
...settings,
wslOnly: enabled,
};
}
function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
return setWslOnly(setWslBackendEnabled(settings, false), false);
}
function readSettings(
fileSystem: FileSystem.FileSystem,
settingsPath: string,
@@ -287,6 +445,12 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
SynchronizedRef.modify(settingsRef, (settings) => {
const nextSettings = update(settings);
return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
});
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
@@ -330,6 +494,18 @@ export const make = Effect.gen(function* () {
);
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
}).pipe(Effect.withSpan("desktop.settings.load")),
setMainWindowBounds: (bounds, isMaximized) =>
persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
Effect.withSpan("desktop.settings.setMainWindowBounds", {
attributes: {
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
isMaximized,
},
}),
),
setServerExposureMode: (mode) =>
persist((settings) => setServerExposureMode(settings, mode)).pipe(
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
@@ -342,6 +518,26 @@ export const make = Effect.gen(function* () {
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
setWslBackendEnabled: (enabled) =>
persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
),
setWslDistro: (distro) =>
persist((settings) => setWslDistro(settings, distro)).pipe(
Effect.withSpan("desktop.settings.setWslDistro", {
attributes: { distro: distro ?? null },
}),
),
setWslOnly: (enabled) =>
persist((settings) => setWslOnly(settings, enabled)).pipe(
Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
),
applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
),
applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
),
});
});
@@ -367,10 +563,18 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: SynchronizedRef.get(settingsRef),
setMainWindowBounds: (bounds, isMaximized) =>
update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
setServerExposureMode: (mode) =>
update((settings) => setServerExposureMode(settings, mode)),
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
setWslBackendEnabled: (enabled) =>
update((settings) => setWslBackendEnabled(settings, enabled)),
setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
applyWslWindowsFallback: update(applyWslWindowsFallback),
applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
});
}),
);
@@ -18,9 +18,9 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -28,7 +28,9 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -75,9 +75,7 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError & {
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
} {
): error is SshPasswordPromptError {
return (
error instanceof SshPasswordPromptError &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
@@ -13,7 +13,7 @@ import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
@@ -38,6 +38,7 @@ const flushCallbacks = Effect.yieldNow;
function makeHarness(options: UpdatesHarnessOptions = {}) {
let checkCount = 0;
let allowDowngrade = false;
let fullChangelog = false;
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
const sentStates: DesktopUpdateState[] = [];
@@ -73,6 +74,10 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setFullChangelog: (value) =>
Effect.sync(() => {
fullChangelog = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
@@ -107,7 +112,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"]);
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: Effect.succeed("Windows"),
start: Effect.void,
stop: () => options.stopBackend ?? Effect.void,
currentConfig: Effect.succeed(Option.none()),
@@ -118,7 +125,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
restartAttempt: 0,
restartScheduled: false,
}),
});
waitForReady: () => Effect.succeed(true),
};
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
@@ -149,9 +158,15 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
@@ -177,6 +192,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
layer,
checkCount: () => checkCount,
feedUrls: () => feedUrls,
fullChangelog: () => fullChangelog,
listenerCount: () =>
Array.from(listeners.values()).reduce(
(total, eventListeners) => total + eventListeners.size,
@@ -278,6 +294,49 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
const harness = makeHarness();
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.setChannel("nightly");
assert.equal(harness.fullChangelog(), true);
harness.emit("update-available", {
version: "1.2.4-nightly.20260709.766",
releaseNotes: [
{
version: "1.2.4-nightly.20260709.766",
note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
},
{
version: "1.2.4-nightly.20260709.765",
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
},
],
});
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "available");
assert.deepEqual(state.releaseNotes, [
{
version: "1.2.4-nightly.20260709.766",
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
},
{
version: "1.2.4-nightly.20260709.765",
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
},
]);
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
+28 -5
View File
@@ -18,7 +18,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
@@ -27,6 +27,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
import {
createInitialDesktopUpdateState,
@@ -49,6 +50,10 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
const UpdateInfo = Schema.Struct({
version: Schema.String,
// Left unvalidated on purpose: a malformed release-notes payload must never
// fail the decode and block the update state transition. The shape is
// validated defensively in normalizeDesktopUpdateReleaseNotes.
releaseNotes: Schema.optional(Schema.Unknown),
});
const DownloadProgressInfo = Schema.Struct({
@@ -241,7 +246,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
export const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const desktopState = yield* DesktopState.DesktopState;
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
const electronWindow = yield* ElectronWindow.ElectronWindow;
@@ -330,10 +335,12 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.setChannel(channel);
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
yield* electronUpdater.setFullChangelog(allowsPrerelease);
yield* logUpdaterInfo("using update channel", {
channel,
allowPrerelease: allowsPrerelease,
allowDowngrade: allowsPrerelease,
fullChangelog: allowsPrerelease,
});
});
@@ -458,7 +465,19 @@ export const make = Effect.gen(function* () {
yield* Ref.set(updateInstallInFlightRef, true);
return yield* Effect.gen(function* () {
yield* backendManager.stop({ timeout: Duration.seconds(5) });
// Stop every backend in the pool, not just the primary. With
// parallel WSL + Windows backends, leaving the WSL instance up
// means quitAndInstall's app.quit() exits before the pool's
// scope cascade has a chance to run its stop finalizer, so the
// WSL child gets hard-killed by the OS instead of receiving
// SIGTERM + grace. Stops run concurrently with the same 5s
// budget the primary had on its own.
const instances = yield* pool.list;
yield* Effect.forEach(
instances,
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
{ concurrency: "unbounded" },
);
yield* electronWindow.destroyAll;
yield* electronUpdater.quitAndInstall({
isSilent: true,
@@ -555,11 +574,15 @@ export const make = Effect.gen(function* () {
}
const checkedAt = yield* currentIsoTimestamp;
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
yield* setState(
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
);
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
yield* logUpdaterInfo("update available", { version: info.version });
yield* logUpdaterInfo("update available", {
version: info.version,
releaseNoteGroups: releaseNotes.length,
});
}),
),
Effect.catchCause((cause) => {
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vite-plus/test";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
describe("normalizeDesktopUpdateReleaseNotes", () => {
it("splits a plain string note into items under the fallback version", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
"## What's changed\n- First fix\n- Second fix",
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
});
it("keeps per-version groups and drops empty ones", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Newer change" },
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
{ version: "1.2.1", note: "- Older change" },
],
"1.2.3",
);
expect(notes).toEqual([
{ version: "1.2.3", items: ["Newer change"] },
{ version: "1.2.1", items: ["Older change"] },
]);
});
it("decodes valid HTML entities", () => {
const notes = normalizeDesktopUpdateReleaseNotes("- Fix &amp; polish &#128512;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
});
it("ignores malformed entries instead of throwing", () => {
const notes = normalizeDesktopUpdateReleaseNotes(
[
{ version: "1.2.3", note: "- Valid change" },
{ version: 42, note: "- Bad version type" },
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
"not an object",
null,
],
"1.2.3",
);
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
});
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
version: `1.3.${9 - index}`,
note: "Full changelog: https://example.com/compare/x...y",
}));
const notes = normalizeDesktopUpdateReleaseNotes(
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
"1.3.9",
);
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
});
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
expect(() =>
normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0"),
).not.toThrow();
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity &#9999999999;", "1.0.0");
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity &#9999999999;"] }]);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
interface ElectronReleaseNoteInfo {
readonly version: string;
readonly note: string | null | undefined;
}
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
if (typeof value !== "object" || value === null) return false;
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
return (
typeof candidate.version === "string" &&
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
);
}
const MAX_RELEASE_NOTE_GROUPS = 6;
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
amp: "&",
apos: "'",
gt: ">",
lt: "<",
nbsp: " ",
quot: '"',
};
function decodeCodePoint(codePoint: number, entity: string): string {
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
// Number.isFinite alone lets oversized values (e.g. &#9999999999;) through.
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
return `&${entity};`;
}
return String.fromCodePoint(codePoint);
}
function decodeHtmlEntity(entity: string): string {
const named = HTML_ENTITY_REPLACEMENTS[entity];
if (named) return named;
if (entity.startsWith("#x")) {
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
}
if (entity.startsWith("#")) {
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
}
return `&${entity};`;
}
function decodeHtmlEntities(input: string): string {
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
decodeHtmlEntity(entity),
);
}
function stripMarkup(input: string): string {
return decodeHtmlEntities(
input
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<li\b[^>]*>/gi, "\n- ")
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
.replace(/<[^>]*>/g, "")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1"),
);
}
function truncateReleaseNoteItem(item: string): string {
if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
}
function isIgnoredReleaseNoteLine(line: string): boolean {
const normalized = line
.toLowerCase()
.replace(/[*_`#]/g, "")
.trim();
return (
normalized === "" ||
normalized === "what's changed" ||
normalized === "whats changed" ||
normalized === "full changelog" ||
normalized === "new contributors" ||
normalized.startsWith("compare: ") ||
normalized.includes("/compare/")
);
}
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
if (!note) return [];
const items: string[] = [];
for (const rawLine of stripMarkup(note).split("\n")) {
const item = rawLine
.trim()
.replace(/^[-*]\s+/, "")
.replace(/^\d+[.)]\s+/, "")
.replace(/\s+/g, " ");
if (isIgnoredReleaseNoteLine(item)) continue;
items.push(truncateReleaseNoteItem(item));
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
}
return items;
}
export function normalizeDesktopUpdateReleaseNotes(
releaseNotes: unknown,
fallbackVersion: string,
): ReadonlyArray<DesktopUpdateReleaseNote> {
const rawNotes =
typeof releaseNotes === "string"
? [{ version: fallbackVersion, note: releaseNotes }]
: Array.isArray(releaseNotes)
? releaseNotes.filter(isElectronReleaseNoteInfo)
: [];
return rawNotes
.map((entry) => ({
version: entry.version,
items: extractReleaseNoteItems(entry.note),
}))
.filter((entry) => entry.items.length > 0)
.slice(0, MAX_RELEASE_NOTE_GROUPS);
}
@@ -118,6 +118,12 @@ describe("updateMachine", () => {
});
it("tracks available, download start, and progress cleanly", () => {
const releaseNotes = [
{
version: "1.1.0",
items: ["feat: add update release notes"],
},
];
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
@@ -126,15 +132,33 @@ describe("updateMachine", () => {
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
releaseNotes,
);
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(available.channel).toBe("latest");
expect(available.releaseNotes).toBe(releaseNotes);
expect(downloading.releaseNotes).toBe(releaseNotes);
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
expect(progress.errorContext).toBeNull();
});
it("clears release notes when checking again", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
enabled: true,
status: "available",
availableVersion: "1.1.0-nightly.1",
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
},
"2026-03-04T00:00:00.000Z",
);
expect(state.releaseNotes).toEqual([]);
});
});
@@ -1,6 +1,7 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateChannel,
DesktopUpdateReleaseNote,
DesktopUpdateState,
} from "@t3tools/contracts";
@@ -29,6 +30,7 @@ export function createInitialDesktopUpdateState(
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt: null,
message: null,
@@ -45,6 +47,7 @@ export function reduceDesktopUpdateStateOnCheckStart(
...state,
status: "checking",
checkedAt,
releaseNotes: [],
message: null,
downloadPercent: null,
errorContext: null,
@@ -72,12 +75,14 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
state: DesktopUpdateState,
version: string,
checkedAt: string,
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
): DesktopUpdateState {
return {
...state,
status: "available",
availableVersion: version,
downloadedVersion: null,
releaseNotes,
downloadPercent: null,
checkedAt,
message: null,
@@ -95,6 +100,7 @@ export function reduceDesktopUpdateStateOnNoUpdate(
status: "up-to-date",
availableVersion: null,
downloadedVersion: null,
releaseNotes: [],
downloadPercent: null,
checkedAt,
message: null,
@@ -73,7 +73,10 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
handleBackendReady: Effect.void,
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
+827 -5
View File
@@ -1,11 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as Electron from "electron";
import { vi } from "vite-plus/test";
vi.mock("electron", async (importOriginal) => ({
@@ -17,16 +23,25 @@ vi.mock("electron", async (importOriginal) => ({
setUserAgent: vi.fn(),
})),
},
screen: {
getAllDisplays: vi.fn(() => [
{
bounds: { x: 0, y: 0, width: 1920, height: 1080 },
},
]),
},
}));
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.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 { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -44,28 +59,41 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
setWindowOpenHandler: vi.fn(),
};
const window = {
close: vi.fn(),
focus: vi.fn(),
getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
isDestroyed: vi.fn(() => false),
isFullScreen: vi.fn(() => false),
isMaximized: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
loadURL: vi.fn(() => Promise.resolve()),
on: vi.fn(),
once: vi.fn(),
maximize: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
once: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
setAutoHideCursor: vi.fn(),
@@ -77,10 +105,20 @@ function makeFakeBrowserWindow() {
return {
window: window as unknown as Electron.BrowserWindow,
getBounds: window.getBounds,
getNormalBounds: window.getNormalBounds,
isDestroyed: window.isDestroyed,
isFullScreen: window.isFullScreen,
isMaximized: window.isMaximized,
isMinimized: window.isMinimized,
loadURL: window.loadURL,
maximize: window.maximize,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
windowListeners,
};
}
@@ -132,13 +170,57 @@ const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
),
);
const desktopWindowBoundsEquivalence = Schema.toEquivalence(
DesktopAppSettings.DesktopWindowBoundsSchema,
);
function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
readonly desktopSettings?: DesktopAppSettings.DesktopSettings;
readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[];
readonly mainWindowMaximizedUpdates?: boolean[];
readonly beforeMainWindowBoundsUpdate?: (
bounds: DesktopAppSettings.DesktopWindowBounds,
) => Effect.Effect<void>;
readonly openedExternalUrls?: unknown[];
}) {
let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.sync(() => desktopSettings),
load: Effect.sync(() => desktopSettings),
setMainWindowBounds: (bounds, isMaximized) =>
Effect.gen(function* () {
if (input.beforeMainWindowBoundsUpdate) {
yield* input.beforeMainWindowBoundsUpdate(bounds);
}
const changed =
desktopSettings.mainWindowBounds === null ||
!desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) ||
desktopSettings.mainWindowMaximized !== isMaximized;
if (changed) {
desktopSettings = {
...desktopSettings,
mainWindowBounds: bounds,
mainWindowMaximized: isMaximized,
};
input.mainWindowBoundsUpdates?.push(bounds);
input.mainWindowMaximizedUpdates?.push(isMaximized);
}
return { settings: desktopSettings, changed };
}),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: (options) =>
Effect.sync(() => {
@@ -163,6 +245,7 @@ function makeTestLayer(input: {
Layer.mergeAll(
desktopAssetsLayer,
desktopEnvironmentLayer,
desktopAppSettingsLayer,
desktopServerExposureLayer,
DesktopState.layer,
electronMenuLayer,
@@ -187,7 +270,119 @@ function makeTestLayer(input: {
);
}
// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
// given outcomes in order (null => simulated open failure), and whose
// currentMainOrFirst mirrors the real fallback to the first live window (the
// splash, before any main is registered). Reveal targets are recorded so tests
// can assert what activation actually surfaced.
const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
Effect.gen(function* () {
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
const createCalls = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
const fallbackWindow = createOutcomes.find(
(window): window is Electron.BrowserWindow => window !== null,
);
const currentMainOrFirst = Effect.gen(function* () {
const registered = yield* Ref.get(mainWindow);
if (Option.isSome(registered)) {
return registered;
}
const created = yield* Ref.get(createdWindows);
return Option.fromNullishOr(created[0] ?? null);
});
const electronWindowShape = {
create: () =>
Effect.gen(function* () {
const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
const outcome = createOutcomes[index] ?? null;
if (outcome === null) {
return yield* new ElectronWindow.ElectronWindowCreateError({
options: {
title: null,
width: null,
height: null,
minWidth: null,
minHeight: null,
show: null,
modal: null,
frame: null,
transparent: null,
backgroundColor: null,
webPreferences: {
preload: null,
partition: null,
sandbox: null,
contextIsolation: null,
nodeIntegration: null,
webviewTag: null,
},
},
cause: new Error("simulated window-open failure"),
});
}
yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
return outcome;
}),
main: Ref.get(mainWindow),
currentMainOrFirst,
focusedMainOrFirst: currentMainOrFirst,
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
clearMain: () => Ref.set(mainWindow, Option.none()),
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
sendAll: () => Effect.void,
destroyAll: Effect.void,
syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
} satisfies ElectronWindow.ElectronWindow["Service"];
const layer = DesktopWindow.layer.pipe(
Layer.provide(
Layer.mergeAll(
desktopAssetsLayer,
desktopEnvironmentLayer,
DesktopAppSettings.layerTest(),
desktopServerExposureLayer,
electronMenuLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: () => Effect.succeed(true),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShell["Service"]),
electronThemeLayer,
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
Layer.mock(PreviewManager.PreviewManager)({
getBrowserSession: () => Effect.succeed({} as Electron.Session),
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
}),
),
),
);
return { layer, createCalls, mainWindow, revealedWindows } as const;
});
describe("DesktopWindow", () => {
it("restores bounds only when the window fits within a connected display", () => {
const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
const displays = [
{ x: 0, y: 0, width: 1920, height: 1080 },
{ x: 1920, y: 0, width: 2560, height: 1440 },
];
assert.deepEqual(
DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
persistedBounds,
);
assert.deepEqual(
DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
);
});
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
@@ -227,8 +422,12 @@ describe("DesktopWindow", () => {
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(createCount), 0);
yield* desktopWindow.handleBackendReady;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(yield* Ref.get(createCount), 1);
assert.equal(createdWindowOptions[0]?.width, 1100);
assert.equal(createdWindowOptions[0]?.height, 780);
assert.isUndefined(createdWindowOptions[0]?.x);
assert.isUndefined(createdWindowOptions[0]?.y);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
@@ -237,6 +436,525 @@ describe("DesktopWindow", () => {
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
createdWindowOptions,
desktopSettings: {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
},
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(createdWindowOptions[0]?.width, 1320);
assert.equal(createdWindowOptions[0]?.height, 880);
assert.equal(createdWindowOptions[0]?.x, 120);
assert.equal(createdWindowOptions[0]?.y, 80);
}).pipe(Effect.provide(layer));
}),
);
it.effect("restores the persisted maximized state", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
desktopSettings: {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
mainWindowMaximized: true,
},
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(fakeWindow.maximize.mock.calls.length, 0);
const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
if (!readyToShow) {
return yield* Effect.die("window ready-to-show listener was not registered");
}
readyToShow();
assert.equal(fakeWindow.maximize.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
);
it.effect("debounces move and resize bounds updates", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const move = fakeWindow.windowListeners.get("move");
const resize = fakeWindow.windowListeners.get("resize");
if (!move || !resize) {
return yield* Effect.die("window bounds listeners were not registered");
}
fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
move();
yield* TestClock.adjust(250);
fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
resize();
yield* TestClock.adjust(499);
assert.deepEqual(mainWindowBoundsUpdates, []);
yield* TestClock.adjust(1);
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("persists normal bounds and state for a maximized window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.isMaximized.mockReturnValue(true);
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const mainWindowMaximizedUpdates: boolean[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
mainWindowMaximizedUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const close = fakeWindow.windowListeners.get("close");
if (!close) {
return yield* Effect.die("window close listener was not registered");
}
close();
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
assert.deepEqual(mainWindowMaximizedUpdates, [true]);
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it.effect("persists normal bounds and state from the native maximize event", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const mainWindowMaximizedUpdates: boolean[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
mainWindowMaximizedUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const maximize = fakeWindow.windowListeners.get("maximize");
if (!maximize) {
return yield* Effect.die("window maximize listener was not registered");
}
fakeWindow.isMaximized.mockReturnValue(true);
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
maximize();
yield* TestClock.adjust(500);
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
assert.deepEqual(mainWindowMaximizedUpdates, [true]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("does not persist bounds that fail the domain schema", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const resize = fakeWindow.windowListeners.get("resize");
if (!resize) {
return yield* Effect.die("window resize listener was not registered");
}
resize();
yield* TestClock.adjust(500);
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, []);
}).pipe(Effect.provide(layer));
}),
);
it.effect("preserves unrestorable bounds until the user changes the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
desktopSettings: {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
},
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const close = fakeWindow.windowListeners.get("close");
const move = fakeWindow.windowListeners.get("move");
if (!close || !move) {
return yield* Effect.die("window lifecycle listeners were not registered");
}
close();
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, []);
fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
move();
yield* TestClock.adjust(500);
yield* Effect.promise(() => Promise.resolve());
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const resize = fakeWindow.windowListeners.get("resize");
if (!resize) {
return yield* Effect.die("window resize listener was not registered");
}
resize();
yield* TestClock.adjust(250);
fakeWindow.isFullScreen.mockReturnValue(true);
yield* desktopWindow.flushMainWindowBounds;
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
);
it.effect("flushes normal bounds when minimized before the debounce completes", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const resize = fakeWindow.windowListeners.get("resize");
if (!resize) {
return yield* Effect.die("window resize listener was not registered");
}
resize();
yield* TestClock.adjust(250);
fakeWindow.isMinimized.mockReturnValue(true);
yield* desktopWindow.flushMainWindowBounds;
assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
}).pipe(Effect.provide(layer));
}),
);
it.effect("logs display lookup failures before falling back to the default size", () =>
Effect.gen(function* () {
const displayLookupFailure = new Error("screen API unavailable");
vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
throw displayLookupFailure;
});
const logRecords: Array<{
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}> = [];
const logger = Logger.make(({ fiber, message }) => {
logRecords.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
createdWindowOptions,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
}).pipe(
Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
);
const warning = logRecords.find(
(record) =>
Array.isArray(record.message) &&
record.message[0] === "failed to read connected displays; using defaults",
);
assert.isDefined(warning);
assert.strictEqual(warning.annotations.cause, displayLookupFailure);
assert.equal(createdWindowOptions[0]?.width, 1100);
assert.equal(createdWindowOptions[0]?.height, 780);
assert.isUndefined(createdWindowOptions[0]?.x);
assert.isUndefined(createdWindowOptions[0]?.y);
}),
);
it.effect("persists the current main window bounds before the window closes", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
const writeStarted = yield* Deferred.make<void>();
const allowWrite = yield* Deferred.make<void>();
const flushCompleted = yield* Deferred.make<void>();
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
mainWindowBoundsUpdates,
beforeMainWindowBoundsUpdate: () =>
Deferred.succeed(writeStarted, undefined).pipe(
Effect.andThen(Deferred.await(allowWrite)),
Effect.asVoid,
),
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const close = fakeWindow.windowListeners.get("close");
if (!close) {
return yield* Effect.die("window close listener was not registered");
}
close();
yield* Deferred.await(writeStarted);
fakeWindow.isDestroyed.mockReturnValue(true);
const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
Effect.forkChild({ startImmediately: true }),
);
yield* Effect.yieldNow;
assert.isFalse(yield* Deferred.isDone(flushCompleted));
yield* Deferred.succeed(allowWrite, undefined);
yield* Fiber.join(flushFiber);
assert.isTrue(yield* Deferred.isDone(flushCompleted));
assert.deepEqual(mainWindowBoundsUpdates, [
{
x: 240,
y: 160,
width: 1410,
height: 930,
},
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
if (!enterFullscreen || !leaveFullscreen) {
return yield* Effect.die("fullscreen listeners were not registered");
}
enterFullscreen();
leaveFullscreen();
assert.deepEqual(fakeWindow.send.mock.calls, [
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
if (!didFailLoad || !didFinishLoad) {
return yield* Effect.die("renderer load listeners were not registered");
}
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
yield* TestClock.adjust(100);
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
["t3code-dev://app/"],
["t3code-dev://app/"],
]);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
didFinishLoad();
yield* TestClock.adjust(250);
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it("retries only transient failures for the development renderer", () => {
assert.isTrue(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -3,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "https://example.com/",
}),
);
});
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
@@ -252,7 +970,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
@@ -274,4 +992,108 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(layer));
}),
);
it.effect(
"retries opening the real main on activate when a failed post-readiness open left only the splash",
() =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
// create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
// window-open error), #3 -> the real main on activate's retry.
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
// 1. WSL-only boot shows the connecting splash.
yield* desktopWindow.showConnectingSplash;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
// 2. Backend reports ready, but opening the real main fails. The pool
// swallows that error in production, so handleBackendReady fails
// here without a registered main window -- only the splash is open.
const readyExit = yield* Effect.exit(
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
);
assert.equal(readyExit._tag, "Failure");
assert.equal(yield* Ref.get(scenario.createCalls), 2);
assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
// 3. Activating must not mistake the splash for the main window: it
// retries the open and brings up the real main instead of leaving
// the user stranded on "Connecting to WSL".
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(scenario.createCalls), 3);
const registeredMain = yield* Ref.get(scenario.mainWindow);
assert.isTrue(Option.isSome(registeredMain));
assert.equal(Option.getOrThrow(registeredMain), main.window);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect(
"re-reveals the connecting splash on activate while the backend is still cold-booting",
() =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
// Only the splash is ever created; the backend never reports ready.
const scenario = yield* makeSplashScenario([splash.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
// Taskbar/dock activation during cold boot must bring the splash back
// rather than no-op and leave it hidden until the backend finishes.
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
yield* desktopWindow.dispatchMenuAction("open-settings");
assert.equal(yield* Ref.get(scenario.createCalls), 1);
assert.equal(splash.send.mock.calls.length, 0);
assert.equal(main.send.mock.calls.length, 0);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
const readyExit = yield* Effect.exit(
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
);
assert.equal(readyExit._tag, "Failure");
yield* desktopWindow.dispatchMenuAction("open-settings");
assert.equal(yield* Ref.get(scenario.createCalls), 3);
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
}).pipe(Effect.provide(scenario.layer));
}),
);
});
+422 -29
View File
@@ -1,27 +1,39 @@
import * as Context from "effect/Context";
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 Ref from "effect/Ref";
import type * as Electron from "electron";
import * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
-102, // ERR_CONNECTION_REFUSED
-105, // ERR_NAME_NOT_RESOLVED
-106, // ERR_INTERNET_DISCONNECTED
-118, // ERR_CONNECTION_TIMED_OUT
]);
type WindowTitleBarOptions = Pick<
Electron.BrowserWindowConstructorOptions,
@@ -31,7 +43,7 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopState.DesktopState
| DesktopAppSettings.DesktopAppSettings
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -50,7 +62,23 @@ export class DesktopWindow extends Context.Service<
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly activate: Effect.Effect<void, DesktopWindowError>;
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
// Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
// mode), before the WSL backend that serves the renderer is ready. It is
// dismissed automatically once the real main window reveals.
readonly showConnectingSplash: Effect.Effect<void>;
// Marks the primary backend as ready so `createMainIfBackendReady` and the
// macOS "activate without windows" path may open the real main window. The
// renderer now always loads the local client URL (getDesktopUrl) and connects
// to the backend through the connection layer, so the reported httpBaseUrl is
// no longer used to point the window at the backend — it is kept only for the
// readiness log and to preserve the callback contract the backend pool drives.
readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
// Called when the backend transitions back to "not ready" (clean stop,
// restart, crash). Clears the latch that lets `activate` auto-create a
// window so a "macOS dock click" while the backend is down doesn't
// produce a stranded window pointing at nothing.
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
@@ -75,6 +103,57 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
function windowFitsWithinDisplay(
windowBounds: DesktopAppSettings.DesktopWindowBounds,
displayBounds: DisplayBounds,
): boolean {
return (
windowBounds.x >= displayBounds.x &&
windowBounds.y >= displayBounds.y &&
windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
);
}
function windowBoundsEqual(
left: DesktopAppSettings.DesktopWindowBounds,
right: DesktopAppSettings.DesktopWindowBounds,
): boolean {
return (
left.x === right.x &&
left.y === right.y &&
left.width === right.width &&
left.height === right.height
);
}
export function resolveInitialMainWindowBounds(
persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
displays: readonly DisplayBounds[],
): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
if (
persistedBounds !== null &&
displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
) {
return persistedBounds;
}
return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
}
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
}
export function isSameOriginRendererNavigation(input: {
readonly applicationUrl: string;
readonly navigationUrl: string;
@@ -86,6 +165,22 @@ export function isSameOriginRendererNavigation(input: {
}
}
export function isRetryableDevelopmentRendererLoadFailure(input: {
readonly applicationUrl: string;
readonly errorCode: number;
readonly isMainFrame: boolean;
readonly validatedUrl: string;
}): boolean {
return (
input.isMainFrame &&
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
isSameOriginRendererNavigation({
applicationUrl: input.applicationUrl,
navigationUrl: input.validatedUrl,
})
);
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -150,9 +245,46 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const state = yield* DesktopState.DesktopState;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
// Window-side latch for the primary backend's readiness. Set by
// handleBackendReady (driven by the pool's onReady callback), cleared
// by handleBackendNotReady (driven by onShutdown). Only consumed by
// createMainIfBackendReady, which gates the post-readiness window
// open in development and the macOS "activate without windows" path.
const backendReadyRef = yield* Ref.make(false);
// The transient "Connecting to WSL" splash window, tracked separately so it
// is never mistaken for the real main window.
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
const dismissConnectingSplash = Effect.gen(function* () {
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
if (Option.isSome(splash) && !splash.value.isDestroyed()) {
splash.value.close();
}
});
// currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
// which during WSL-only boot is the connecting splash. The splash is never
// registered via setMain, so it must be treated as "no real main window" --
// otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
// open (or retry) the real main. That is the failure the pool's swallowed
// post-readiness window-open error would otherwise strand the user in:
// splash up, backend ready, no main, and activation only re-reveals splash.
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
Ref.get(splashWindowRef).pipe(
Effect.map((splash) =>
Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
? Option.none<Electron.BrowserWindow>()
: window,
),
);
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
@@ -163,9 +295,31 @@ export const make = Effect.gen(function* () {
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
const persistedSettings = yield* desktopSettings.get;
const persistedBounds = persistedSettings.mainWindowBounds;
const displayBoundsResult = yield* Effect.sync(() => {
try {
return {
_tag: "Success" as const,
bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
};
} catch (cause) {
return { _tag: "Failure" as const, cause };
}
});
const displayBounds =
displayBoundsResult._tag === "Success"
? displayBoundsResult.bounds
: yield* logWindowWarning("failed to read connected displays; using defaults", {
cause: displayBoundsResult.cause,
}).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
}
const window = yield* electronWindow.create({
width: 1100,
height: 780,
...initialBounds,
minWidth: 840,
minHeight: 620,
show: false,
@@ -187,6 +341,92 @@ export const make = Effect.gen(function* () {
if (environment.platform === "darwin") {
window.setAutoHideCursor(false);
}
let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
if (window.isDestroyed()) {
return null;
}
const bounds =
window.isFullScreen() || window.isMaximized() || window.isMinimized()
? window.getNormalBounds()
: window.getBounds();
return DesktopAppSettings.normalizeMainWindowBounds({
x: Math.round(bounds.x),
y: Math.round(bounds.y),
width: Math.round(bounds.width),
height: Math.round(bounds.height),
});
};
const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
if (!boundsPersistenceEnabled) {
return pendingBoundsPersistFiber;
}
const bounds = readPersistableBounds();
if (bounds === null) {
return pendingBoundsPersistFiber;
}
pendingBoundsPersistFiber = runFork(
desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
Effect.asVoid,
Effect.catch((error) =>
logWindowWarning("failed to persist main window bounds", {
message: error.message,
}),
),
),
);
return pendingBoundsPersistFiber;
};
const scheduleBoundsPersist = () => {
if (!boundsPersistenceEnabled) {
const currentBounds = readPersistableBounds();
if (
currentBounds === null ||
(fallbackWindowBounds !== null &&
windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
window.isMaximized() === fallbackWindowMaximized)
) {
return;
}
}
boundsPersistenceEnabled = true;
if (boundsPersistFiber !== undefined) {
const fiber = boundsPersistFiber;
boundsPersistFiber = undefined;
runFork(Fiber.interrupt(fiber));
}
boundsPersistFiber = runFork(
Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
Effect.andThen(
Effect.sync(() => {
boundsPersistFiber = undefined;
void persistCurrentBounds();
}),
),
),
);
};
const clearBoundsPersist = () => {
if (boundsPersistFiber === undefined) {
return;
}
const fiber = boundsPersistFiber;
boundsPersistFiber = undefined;
runFork(Fiber.interrupt(fiber));
};
const flushBoundsPersist = Effect.sync(() => {
clearBoundsPersist();
return persistCurrentBounds();
}).pipe(
Effect.flatMap((fiber) =>
fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
),
);
flushMainWindowBounds = flushBoundsPersist;
yield* previewManager.setMainWindow(window);
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
@@ -226,9 +466,7 @@ export const make = Effect.gen(function* () {
{
label: "Copy Link",
click: () => {
void runPromise(
electronShell.copyText(params.linkURL).pipe(Effect.ignore({ log: true })),
);
void runPromise(electronShell.copyText(params.linkURL));
},
},
{ type: "separator" },
@@ -255,7 +493,7 @@ export const make = Effect.gen(function* () {
window.webContents.setWindowOpenHandler(({ url }) => {
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
void runPromise(electronShell.openExternal(url));
}
return { action: "deny" };
});
@@ -271,7 +509,7 @@ export const make = Effect.gen(function* () {
event.preventDefault();
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
void runPromise(electronShell.openExternal(url));
}
});
@@ -279,7 +517,77 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
window.on("resize", scheduleBoundsPersist);
window.on("move", scheduleBoundsPersist);
window.on("maximize", scheduleBoundsPersist);
window.on("unmaximize", scheduleBoundsPersist);
window.on("close", () => {
runFork(flushBoundsPersist);
});
if (environment.platform === "darwin") {
window.on("enter-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
});
window.on("leave-full-screen", () => {
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
});
}
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
}
const retryFiber = developmentLoadRetryFiber;
developmentLoadRetryFiber = undefined;
runFork(Fiber.interrupt(retryFiber));
};
const loadApplication = () => {
if (window.isDestroyed()) {
return;
}
void window.loadURL(applicationUrl).catch(() => undefined);
};
const scheduleDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
return undefined;
}
const retryIndex = Math.min(
developmentLoadRetryIndex,
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
);
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
developmentLoadRetryIndex += 1;
developmentLoadRetryFiber = runFork(
Effect.sleep(retryInMs).pipe(
Effect.andThen(
Effect.sync(() => {
developmentLoadRetryFiber = undefined;
if (!window.isDestroyed()) {
loadApplication();
}
}),
),
),
);
return retryInMs;
};
window.webContents.on("did-finish-load", () => {
if (
environment.isDevelopment &&
!isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: window.webContents.getURL(),
})
) {
return;
}
clearDevelopmentLoadRetry();
developmentLoadRetryIndex = 0;
window.setTitle(environment.displayName);
});
window.webContents.on(
@@ -288,11 +596,22 @@ export const make = Effect.gen(function* () {
if (!isMainFrame) {
return;
}
const retryInMs =
environment.isDevelopment &&
isRetryableDevelopmentRendererLoadFailure({
applicationUrl,
errorCode,
isMainFrame,
validatedUrl: validatedURL,
})
? scheduleDevelopmentLoadRetry()
: undefined;
void runPromise(
logWindowWarning("main window failed to load", {
errorCode,
errorDescription,
url: validatedURL,
...(retryInMs === undefined ? {} : { retryInMs }),
}),
);
},
@@ -311,17 +630,22 @@ export const make = Effect.gen(function* () {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
void runPromise(electronWindow.reveal(window));
// Reveal the real window, then close the connecting splash (if any) so the
// two don't overlap and there's no blank gap between them.
if (persistedSettings.mainWindowMaximized) {
window.maximize();
}
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
});
loadApplication();
if (environment.isDevelopment) {
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
clearDevelopmentLoadRetry();
clearBoundsPersist();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
@@ -336,7 +660,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.createMain"));
const ensureMain = Effect.gen(function* () {
const existingWindow = yield* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
return existingWindow.value;
}
@@ -350,35 +674,104 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
const createMainIfBackendReady = Effect.gen(function* () {
const backendReady = yield* Ref.get(state.backendReady);
const backendReady = yield* Ref.get(backendReadyRef);
if (!backendReady) return;
const existingWindow = yield* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) return;
yield* createMain;
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
const showConnectingSplash = Effect.gen(function* () {
// Only when nothing is shown yet: no real window, no existing splash.
const existingSplash = yield* Ref.get(splashWindowRef);
if (Option.isSome(existingSplash)) return;
const existingWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(existingWindow)) return;
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
const splash = yield* electronWindow.create({
width: 360,
height: 220,
resizable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
frame: false,
center: true,
show: false,
skipTaskbar: false,
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
title: environment.displayName,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
yield* Ref.set(splashWindowRef, Option.some(splash));
splash.once("closed", () => {
void runPromise(Ref.set(splashWindowRef, Option.none()));
});
splash.once("ready-to-show", () => {
if (!splash.isDestroyed()) {
splash.show();
}
});
void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
yield* logWindowInfo("connecting splash shown");
}).pipe(
// The splash is best-effort UX — never let it fail startup.
Effect.catch((error) =>
logWindowWarning("failed to show connecting splash", { message: error.message }),
),
Effect.withSpan("desktop.window.showConnectingSplash"),
);
return DesktopWindow.of({
createMain,
ensureMain,
revealOrCreateMain,
activate: Effect.gen(function* () {
const existingWindow = yield* electronWindow.currentMainOrFirst;
const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
yield* electronWindow.reveal(existingWindow.value);
} else {
yield* createMainIfBackendReady;
return;
}
// No real main window yet. While the backend is still cold-booting,
// re-reveal the connecting splash so taskbar/dock activation brings it
// back instead of doing nothing. Once the backend is ready we fall
// through to (re)create the real main -- including retrying a previously
// failed open the pool swallowed -- rather than latching onto the splash.
const backendReady = yield* Ref.get(backendReadyRef);
if (!backendReady) {
const splash = yield* Ref.get(splashWindowRef);
if (Option.isSome(splash)) {
yield* electronWindow.reveal(splash.value);
return;
}
}
yield* createMainIfBackendReady;
}).pipe(Effect.withSpan("desktop.window.activate")),
createMainIfBackendReady,
handleBackendReady: Effect.gen(function* () {
yield* Ref.set(state.backendReady, true);
yield* logWindowInfo("backend ready", { source: "http" });
showConnectingSplash,
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
yield* Ref.set(backendReadyRef, true);
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
yield* createMainIfBackendReady;
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
}),
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
Effect.withSpan("desktop.window.handleBackendNotReady"),
),
flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
Effect.withSpan("desktop.window.flushMainWindowBounds"),
),
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
yield* Effect.annotateCurrentSpan({ action });
const existingWindow = yield* electronWindow.focusedMainOrFirst;
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
const existingWindow = yield* focusedMainWindow;
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
return;
}
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
const send = () => {
if (targetWindow.isDestroyed()) return;
@@ -0,0 +1,199 @@
import { assert, describe, it } from "@effect/vitest";
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 NetService from "@t3tools/shared/Net";
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import type {
DesktopBackendSnapshot,
DesktopBackendStartConfig,
} from "../backend/DesktopBackendManager.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
import * as DesktopWslBackend from "./DesktopWslBackend.ts";
function makeStubInstance(input: {
readonly id: DesktopBackendPool.BackendInstanceId;
readonly label: string;
readonly snapshot: DesktopBackendSnapshot;
readonly start?: Effect.Effect<void>;
}): DesktopBackendPool.DesktopBackendInstance {
return {
id: input.id,
label: Effect.succeed(input.label),
start: input.start ?? Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
snapshot: Effect.succeed(input.snapshot),
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
};
}
const idleSnapshot: DesktopBackendSnapshot = {
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 5,
restartScheduled: false,
};
const primarySnapshot: DesktopBackendSnapshot = {
desiredRunning: true,
ready: true,
activePid: Option.some(123),
restartAttempt: 0,
restartScheduled: false,
};
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
port: 3773,
bindHost: "127.0.0.1",
httpBaseUrl: new URL("http://127.0.0.1:3773"),
tailscaleServeEnabled: false,
tailscaleServePort: 443,
}),
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
const backendConfigurationLayer = Layer.succeed(
DesktopBackendConfiguration.DesktopBackendConfiguration,
{
resolvePrimary: Effect.die("unexpected resolvePrimary"),
resolvePrimaryLabel: Effect.succeed("Windows"),
resolveWsl: () => Effect.die("unexpected resolveWsl"),
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
);
const netLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
} satisfies NetService.NetService["Service"]);
describe("DesktopWslBackend", () => {
it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
const primary = makeStubInstance({
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: "Windows",
snapshot: primarySnapshot,
});
const wsl = makeStubInstance({
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
label: "WSL (Ubuntu)",
snapshot: primarySnapshot,
});
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
get: (id) =>
Effect.succeed(
id === DesktopBackendPool.PRIMARY_INSTANCE_ID
? Option.some(primary)
: Option.none<DesktopBackendPool.DesktopBackendInstance>(),
),
list: Effect.succeed([primary]),
primary: Effect.succeed(primary),
register: (spec) =>
Effect.sync(() => {
registeredSpec = spec;
return wsl;
}),
unregister: () => Effect.die("unexpected unregister"),
} satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
return Effect.gen(function* () {
const backend = yield* DesktopWslBackend.DesktopWslBackend;
yield* backend.reconcile;
const spec = registeredSpec;
assert.isDefined(spec);
if (spec === undefined) {
throw new Error("Expected WSL backend registration");
}
const recordFailure = spec.onPreflightFailed;
const clearFailure = spec.onReady;
assert.isDefined(recordFailure);
assert.isDefined(clearFailure);
if (recordFailure === undefined || clearFailure === undefined) {
throw new Error("Expected WSL backend callbacks");
}
assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
yield* clearFailure(new URL("http://127.0.0.1:41773"));
assert.deepEqual(yield* backend.lastPreflightError, Option.none());
}).pipe(
Effect.provide(
DesktopWslBackend.layer.pipe(
Layer.provideMerge(poolLayer),
Layer.provideMerge(backendConfigurationLayer),
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(netLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslDistro: "Ubuntu",
wslOnly: false,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
),
),
);
});
it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
let startCount = 0;
const primary = makeStubInstance({
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: "Windows",
snapshot: primarySnapshot,
});
const wsl = makeStubInstance({
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
label: "WSL (Ubuntu)",
snapshot: idleSnapshot,
start: Effect.sync(() => {
startCount += 1;
}),
});
return Effect.gen(function* () {
const backend = yield* DesktopWslBackend.DesktopWslBackend;
yield* backend.reconcile;
assert.equal(startCount, 1);
}).pipe(
Effect.provide(
DesktopWslBackend.layer.pipe(
Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
Layer.provideMerge(backendConfigurationLayer),
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(netLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslDistro: "Ubuntu",
wslOnly: false,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
),
),
);
});
});
+268
View File
@@ -0,0 +1,268 @@
// Orchestrator that keeps the WSL pool instance in sync with the user's
// settings. `reconcile` is the single entry point — bootstrap calls it
// once after the primary backend starts, and the wsl.ts IPC calls it
// after persisting a `wslBackendEnabled` or `wslDistro` change. The
// effect is idempotent and never fails: errors (WSL not available, port
// allocation failed, register failed) get logged and reconcile returns
// having left the pool in a consistent state (either the previous WSL
// instance is still running, or none is).
//
// The instance id encodes the desired distro selection — `wsl:default`
// when the user picked "track the WSL default" (settings.wslDistro is
// null) and `wsl:<distro>` otherwise. Changing the distro setting
// changes the id, so reconcile unregisters the old instance before
// registering the new one. The label that the frontend env switcher
// renders is derived from the same field.
//
// Port allocation: each WSL instance gets a freshly scanned port to
// avoid colliding with the primary or with a previously-registered WSL
// instance that's still tearing down. The scan only checks loopback
// (127.0.0.1) since the WSL backend is loopback-only — the primary
// owns LAN exposure when the user opts in.
import * as Cause from "effect/Cause";
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 Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
import * as NetService from "@t3tools/shared/Net";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
// Exported so callers that parse pool ids (e.g. the pickFolder IPC
// handler in ipc/methods/window.ts) reference the same prefix this
// module produces. Keeping it inline in two places risks silent
// divergence if one ever gets renamed.
export const WSL_INSTANCE_ID_PREFIX = "wsl:";
const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
const MAX_TCP_PORT = 65_535;
export class DesktopWslBackend extends Context.Service<
DesktopWslBackend,
{
// Bring the pool in line with the current persisted WSL settings.
// Idempotent. Never fails (errors are logged); callers can chain it
// after persisting settings without an error-handling dance.
readonly reconcile: Effect.Effect<void>;
// Reason the dual-mode WSL secondary last failed preflight (no node, wrong
// version, missing build tools), or None. Read by the getWslState IPC so
// Connections settings can show it inline. None in wsl-only mode (that path
// surfaces via a dialog + Windows fallback).
readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
DesktopObservability.makeComponentLogger("desktop-wsl-backend");
const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
DesktopBackendPool.BackendInstanceId(
distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
);
const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
id.startsWith(WSL_INSTANCE_ID_PREFIX);
const buildLabel = (distro: string | null): string =>
distro === null ? "WSL (default distro)" : `WSL (${distro})`;
// Loopback-only port scan starting one above the primary's port. The
// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
// auto-forwards), so we only need to verify the IPv4 loopback can bind.
const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
startPort: number,
): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
const net = yield* NetService.NetService;
for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
if (yield* net.canListenOnHost(port, "127.0.0.1")) {
return port;
}
}
return yield* new NetService.NetError({
message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
});
});
export const layer = Layer.effect(
DesktopWslBackend,
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const net = yield* NetService.NetService;
// Serialize reconcile so the bootstrap fork and the IPC handlers
// (setWslBackendEnabled, setWslDistro) can't interleave. Without
// this, two reconciles could both observe "no WSL instance
// registered" between their pool reads and both call startNew
// with different distros, leaving the loser stranded.
const reconcileMutex = yield* Semaphore.make(1);
// Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
// inline in Connections settings. The primary's failure is handled by the
// pool (dialog + Windows fallback) instead; here the app stays usable on
// Windows, so we record the reason rather than interrupting. Cleared on any
// reconcile state change so it reflects the current attempt.
const preflightErrorRef = yield* Ref.make(Option.none<string>());
const findExistingWslInstance = pool.list.pipe(
Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
Effect.map(Option.fromNullishOr),
);
const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
pool.unregister(id).pipe(
Effect.catchTags({
DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
// Should never happen — wsl: ids are not the primary id — but
// log loudly if the logic ever drifts.
logWslBackendWarning("refusing to unregister primary as wsl instance", {
id,
error: cause.message,
}),
}),
);
const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
readonly distro: string | null;
}) {
const primaryConfig = yield* serverExposure.backendConfig;
const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
Effect.provideService(NetService.NetService, net),
Effect.map((value) => Option.some(value)),
Effect.catch((error) =>
logWslBackendWarning("could not allocate port for WSL backend", {
error: error.message,
}).pipe(Effect.as(Option.none<number>())),
),
);
if (Option.isNone(port)) {
return;
}
const allocatedPort = port.value;
const targetId = resolveTargetInstanceId(input.distro);
yield* logWslBackendInfo("registering WSL backend with pool", {
id: targetId,
port: allocatedPort,
distro: input.distro ?? null,
});
const instance = yield* pool
.register({
id: targetId,
label: Effect.succeed(buildLabel(input.distro)),
configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
// Dual-mode secondary: record a fatal preflight failure so Connections
// settings can show why the WSL backend never appeared. No dialog or
// fallback — Windows is the primary and keeps working.
onPreflightFailed: (failure) =>
Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
onReady: () => Ref.set(preflightErrorRef, Option.none()),
})
.pipe(
Effect.map((registered) => Option.some(registered)),
Effect.catch((error) =>
logWslBackendWarning("WSL backend already registered, skipping start", {
id: targetId,
error: error.message,
}).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
),
);
yield* Option.match(instance, {
onNone: () => Effect.void,
onSome: (registered) => registered.start,
});
});
const reconcileBody = Effect.gen(function* () {
const settings = yield* appSettings.get;
const available = yield* wslEnvironment.isAvailable;
const existing = yield* findExistingWslInstance;
const existingId = Option.map(existing, (instance) => instance.id);
// In wsl-only mode the pool's primary IS the WSL backend (see
// DesktopBackendConfiguration.resolvePrimary), so the
// orchestrator skips registering a parallel "wsl:<distro>"
// secondary. Without this skip we'd spin up two WSL processes
// on the same distro for users who explicitly asked for one.
const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
const targetId = shouldRun
? Option.some(resolveTargetInstanceId(settings.wslDistro))
: Option.none<DesktopBackendPool.BackendInstanceId>();
// No-op if the desired state already matches what's registered.
if (Option.isNone(targetId) && Option.isNone(existingId)) {
return;
}
if (
Option.isSome(targetId) &&
Option.isSome(existing) &&
targetId.value === existing.value.id
) {
const existingInstance = existing.value;
const snapshot = yield* existingInstance.snapshot;
const isIdle =
!snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
if (isIdle) {
yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
yield* Ref.set(preflightErrorRef, Option.none());
yield* existingInstance.start;
}
return;
}
// A real state change is happening (start, stop, or distro swap). Clear
// any stale secondary preflight error so it reflects this fresh attempt;
// onPreflightFailed re-sets it only if the new secondary exhausts retries.
yield* Ref.set(preflightErrorRef, Option.none());
if (Option.isSome(existingId)) {
yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
yield* stopExisting(existingId.value);
}
if (Option.isSome(targetId)) {
// Pre-warm the WSL VM before registering so the readiness probe
// doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
// distro=null (uses the WSL default) and is bounded by its own
// timeout, so it's safe to await unconditionally here.
yield* wslEnvironment.preWarm(settings.wslDistro);
yield* startNew({ distro: settings.wslDistro });
}
});
// Top-level safety net. Every internal step today already catches
// its own failures (port allocation, register, preWarm), so the
// inferred error type is `never` and this catch is a no-op in
// steady state. It's here to enforce the file-header contract
// ("reconcile never fails; errors are logged") if a future change
// introduces an unhandled failure path — otherwise IPC callers
// like setWslBackendEnabled would surface it to the renderer as
// an opaque error.
const reconcile = reconcileMutex
.withPermits(1)(reconcileBody)
.pipe(
Effect.catchCause((cause) =>
logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
),
Effect.withSpan("desktop.wslBackend.reconcile"),
);
return DesktopWslBackend.of({
reconcile,
lastPreflightError: Ref.get(preflightErrorRef),
});
}),
);
@@ -0,0 +1,261 @@
import { describe, it } from "@effect/vitest";
import { expect } from "vite-plus/test";
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 Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildWslNodeEnvPreamble,
DesktopWslDistroListError,
formatMissingToolsReason,
formatNodePtyProbeFailureReason,
formatWslShellTransportFailureReason,
parseNodePath,
parseNodeVersion,
parseResolvedPath,
parseToolchainReport,
probeWslDistros,
} from "./DesktopWslEnvironment.ts";
const encoder = new TextEncoder();
const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
ChildProcessSpawner.make(() =>
Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode:
result.exitCode === undefined
? Effect.never
: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
isRunning: Effect.succeed(result.exitCode === undefined),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
),
);
describe("probeWslDistros", () => {
it.effect("preserves a successful empty distro list", () =>
Effect.gen(function* () {
const distros = yield* probeWslDistros;
expect(distros).toEqual([]);
}).pipe(
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
makeDistroListSpawner({ stdout: "", exitCode: 0 }),
),
),
);
it.effect("fails when the distro-list command exits unsuccessfully", () =>
Effect.gen(function* () {
const error = yield* probeWslDistros.pipe(Effect.flip);
expect(error).toBeInstanceOf(DesktopWslDistroListError);
expect(error.message).toContain("exited with code 1");
}).pipe(
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
makeDistroListSpawner({ exitCode: 1 }),
),
),
);
it.effect("fails when the distro-list command times out", () => {
const layer = Layer.merge(
TestClock.layer(),
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
);
return Effect.gen(function* () {
const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.seconds(8));
const error = yield* Fiber.join(fiber);
expect(error).toBeInstanceOf(DesktopWslDistroListError);
expect(error.message).toContain("timed out");
}).pipe(Effect.provide(layer));
});
});
describe("formatNodePtyProbeFailureReason", () => {
it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
const reason = formatNodePtyProbeFailureReason(4);
expect(reason).toContain("packaged Linux node-pty binary was not included");
expect(reason).toContain("--wsl-prebuild");
});
it("leaves other node-pty load failures to the compatibility diagnostic", () => {
expect(formatNodePtyProbeFailureReason(1)).toBeNull();
});
});
describe("formatWslShellTransportFailureReason", () => {
it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
expect(formatWslShellTransportFailureReason(null)).toBeNull();
});
});
describe("buildWslNodeEnvPreamble", () => {
it("passes the required Node engine range into the shared resolver", () => {
const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
preamble.lastIndexOf("ensure_remote_node_path || true"),
);
});
it("keeps the shared resolver permissive when no Node engine range is provided", () => {
expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
});
});
describe("parseToolchainReport", () => {
it("returns no missing tools and no node version on empty output", () => {
expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
});
it("collects all missing: lines", () => {
const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
expect(parseToolchainReport(stdout)).toEqual({
missingTools: ["make", "g++"],
nodeVersion: "24.10.0",
});
});
it("ignores blank lines and trims whitespace", () => {
const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
expect(parseToolchainReport(stdout)).toEqual({
missingTools: ["python3"],
nodeVersion: "v22.16.0",
});
});
it("returns null node version when value after prefix is empty", () => {
expect(parseToolchainReport("nodeVersion:")).toEqual({
missingTools: [],
nodeVersion: null,
});
});
});
describe("parseNodePath", () => {
it("extracts the absolute node path from a nodePath: line", () => {
const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
});
it("returns null when node was not found (empty value after prefix)", () => {
expect(parseNodePath("nodePath:")).toBeNull();
});
it("returns null when there is no nodePath line at all", () => {
expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
});
it("ignores surrounding noise and trims whitespace", () => {
const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
expect(parseNodePath(stdout)).toBe("/usr/bin/node");
});
});
describe("parseNodeVersion", () => {
it("extracts the node version from a nodeVersion: line", () => {
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
});
it("returns null when the version value is empty", () => {
expect(parseNodeVersion("nodeVersion:")).toBeNull();
});
it("returns null when there is no nodeVersion line at all", () => {
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
});
it("ignores surrounding noise and trims whitespace", () => {
const stdout = [
"some preamble noise",
" nodeVersion:22.16.0 ",
"nodePath:/usr/bin/node",
].join("\n");
expect(parseNodeVersion(stdout)).toBe("22.16.0");
});
});
describe("parseResolvedPath", () => {
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
resolvedPath,
);
});
it("accepts CRLF output without retaining the carriage return", () => {
expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
"/usr/local/bin:/usr/bin",
);
});
it("returns null when the resolved PATH is absent or empty", () => {
expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
});
});
describe("formatMissingToolsReason", () => {
it("returns null when everything is present and node is in range", () => {
expect(
formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
).toBeNull();
});
it("returns null when range is not specified and tools are present", () => {
expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
});
it("flags missing node first", () => {
const reason = formatMissingToolsReason(
{ missingTools: ["node", "make"], nodeVersion: null },
"^24.10",
);
expect(reason).toContain("node");
expect(reason).toContain("^24.10");
expect(reason).toContain("make");
expect(reason).toContain("nvm");
});
it("flags an out-of-range node version with the actual version surfaced", () => {
const reason = formatMissingToolsReason(
{ missingTools: [], nodeVersion: "20.0.0" },
"^24.10 || ^22.16",
);
expect(reason).toContain("node 20.0.0");
expect(reason).toContain("requires ^24.10 || ^22.16");
});
it("flags missing build tools without node when node is fine", () => {
const reason = formatMissingToolsReason(
{ missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
"^24.10",
);
expect(reason).toContain("g++");
expect(reason).toContain("python3");
expect(reason).toContain("build-essential");
expect(reason).not.toContain("nvm");
});
});
@@ -0,0 +1,887 @@
import * as Context from "effect/Context";
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 Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
const LIST_TIMEOUT = Duration.seconds(8);
const PRE_WARM_TIMEOUT = Duration.seconds(10);
const WSLPATH_TIMEOUT = Duration.seconds(10);
const PROBE_TIMEOUT = Duration.seconds(10);
const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
const BUILD_TIMEOUT = Duration.minutes(5);
const USER_HOME_TIMEOUT = Duration.seconds(5);
const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
const BUILD_TRANSPORT_RETRY_LIMIT = 2;
export interface EnsureWslNodePtyOptions {
readonly allowBuild?: boolean;
readonly nodeEngineRange?: string | null;
}
export type EnsureWslNodePtyResult =
| {
readonly ok: true;
readonly nodePath: string;
readonly resolvedPath: string;
}
| {
readonly ok: false;
readonly reason: string;
readonly fatal: boolean;
readonly retryLimit?: number;
};
export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
"DesktopWslDistroListError",
{ reason: Schema.String },
) {
override get message(): string {
return this.reason;
}
}
const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
export class DesktopWslEnvironment extends Context.Service<
DesktopWslEnvironment,
{
readonly isAvailable: Effect.Effect<boolean>;
// Best-effort enumeration for renderer UX. Backend health checks must use
// probeDistros so a transient command failure is not mistaken for a
// successful empty installation.
readonly listDistros: Effect.Effect<readonly WslDistro[]>;
readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
readonly preWarm: (distro: string | null) => Effect.Effect<void>;
readonly windowsToWslPath: (
distro: string | null,
windowsPath: string,
) => Effect.Effect<Option.Option<string>>;
// Resolves the user's Linux home dir inside the chosen distro (e.g.
// "/home/josh"). Used by the folder picker to expand `~` correctly.
readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
// Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
// (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
// httpBaseUrl so the renderer can reach it without relying on wslhost's
// localhost→WSL automatic forwarding, which is flaky in practice
// (the backend can be listening for 30+ seconds before wslhost starts
// forwarding 127.0.0.1:port to WSL-side localhost).
readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
readonly ensureNodePty: (
distro: string | null,
windowsRepoRoot: string,
options?: EnsureWslNodePtyOptions,
) => Effect.Effect<EnsureWslNodePtyResult>;
}
>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
distro ? ["-d", distro] : [];
const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
let totalLength = 0;
for (const arr of arrays) totalLength += arr.byteLength;
const out = new Uint8Array(totalLength);
let offset = 0;
for (const arr of arrays) {
out.set(arr, offset);
offset += arr.byteLength;
}
return out;
};
const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
interface ShellResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
readonly transportFailure: "timeout" | "spawn" | "process" | null;
}
const TIMEOUT_RESULT: ShellResult = {
exitCode: 124,
stdout: "",
stderr: "\n[timeout]",
transportFailure: "timeout",
};
export const formatWslShellTransportFailureReason = (
failure: ShellResult["transportFailure"],
): string | null => {
switch (failure) {
case "timeout":
return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
case "spawn":
return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
case "process":
return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
case null:
return null;
}
};
// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
// the same way. Passing the engine range lets the resolver fall through to
// version managers like nvm when a system node exists but is too old.
export const buildWslNodeEnvPreamble = (
nodeEngineRange?: string | null,
): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
ensure_remote_node_path || true
`;
// wsl.exe re-escapes args before forwarding them to the Linux side, which
// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
// avoid passing it on the command line at all.
const runWslShell = (
distro: string | null,
bashScript: string,
timeout: Duration.Duration,
options: EnsureWslNodePtyOptions = {},
): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
const spawner = ChildProcessSpawner.ChildProcessSpawner;
// -l picks up profile-managed PATH; the shared resolver covers supported
// version managers that non-interactive login shells can miss. -s so bash
// reads the script from stdin.
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
{
stdin: Stream.encodeText(
Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
),
stdout: "pipe",
stderr: "pipe",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
return Effect.scoped(
Effect.gen(function* () {
const spawnerService = yield* spawner;
const spawnResult = yield* spawnerService.spawn(command).pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Failure", error }) as const,
onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
}),
);
if (spawnResult._tag === "Failure") {
return {
exitCode: 127,
stdout: "",
stderr: `\n${spawnResult.error.message}`,
transportFailure: "spawn",
} satisfies ShellResult;
}
const handle = spawnResult.handle;
// Drain stdout and stderr concurrently so neither pipe buffer can fill
// and stall the child (node-gyp rebuild emits large output on both).
const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
[Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
{ concurrency: "unbounded" },
);
return {
exitCode: exitCode as unknown as number,
stdout: decodeUtf8(concatChunks(stdoutBytes)),
stderr: decodeUtf8(concatChunks(stderrBytes)),
transportFailure: null,
} satisfies ShellResult;
}),
).pipe(
Effect.timeoutOption(timeout),
Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
Effect.catch((error) =>
Effect.succeed<ShellResult>({
exitCode: 127,
stdout: "",
stderr: `\n${error.message}`,
transportFailure: "process",
}),
),
);
};
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
: null;
const NODE_PTY_PROBE_SCRIPT = (
linuxServerDir: string,
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The server bundle externalizes its deps to node_modules, and the WSL Node
// can't read inside app.asar, so confirm those deps are unpacked on the real
// filesystem before reporting the backend healthy. "effect" is the framework
// every server module imports; resolving it validates the whole node_modules
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
// report it accurately instead of letting the server crash on
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
// launch with no fallback).
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
const fs = require("node:fs");
const path = require("node:path");
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
// Node versions — require() succeeding IS the real compatibility test. Compare
// only arch and node-pty version (a stale binary from a different node-pty),
// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
// whenever the user's WSL Node ABI differs from the build's, defeating the
// whole point of shipping one prebuilt for all Node versions.
const expected = {
arch: process.arch,
nodePtyVersion: require("node-pty/package.json").version,
};
const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
const binary = path.join(prebuildDir, "pty.node");
if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
require("node-pty");
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
for (const key of Object.keys(expected)) {
if (actual[key] !== expected[key]) process.exit(2);
}
NODE`;
const TOOLCHAIN_CHECK_SCRIPT = [
"for tool in node make g++ python3; do",
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
"done",
"if command -v node >/dev/null 2>&1; then",
` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
"fi",
].join("\n");
const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
[
"set -e",
`cd ${shellQuote(linuxServerDir)}`,
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
`arch=$(node -p "process.arch")`,
`modules=$(node -p "process.versions.modules")`,
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
`cd "$pkg_dir"`,
"npx --yes node-gyp rebuild",
`prebuild_dir="prebuilds/linux-$arch"`,
`mkdir -p "$prebuild_dir"`,
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
`node -e 'require("node-pty")'`,
].join("\n");
export interface ToolchainReport {
readonly missingTools: ReadonlyArray<string>;
readonly nodeVersion: string | null;
}
export const parseToolchainReport = (stdout: string): ToolchainReport => {
const lines = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const missingTools = lines
.filter((line) => line.startsWith("missing:"))
.map((line) => line.slice("missing:".length));
const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
const nodeVersion = nodeVersionLine
? nodeVersionLine.slice("nodeVersion:".length).trim() || null
: null;
return { missingTools, nodeVersion };
};
// Pulls the absolute node path the WSL distro resolved after the shared remote
// resolver repaired PATH. Returns null when no node was found, which the caller
// turns into an actionable "install Node" message instead of a confusing
// node-pty error.
export const parseNodePath = (stdout: string): string | null => {
const path = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.startsWith("nodePath:"))
.map((line) => line.slice("nodePath:".length).trim())
.find((value) => value.length > 0);
return path ?? null;
};
export const parseNodeVersion = (stdout: string): string | null => {
const version = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.startsWith("nodeVersion:"))
.map((line) => line.slice("nodeVersion:".length).trim())
.find((value) => value.length > 0);
return version ?? null;
};
// Captures the login-shell PATH after the shared resolver has loaded version
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
// paths containing spaces or apostrophes can be forwarded as one env argv.
export const parseResolvedPath = (stdout: string): string | null => {
const prefix = "resolvedPath:";
const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
if (line === undefined) return null;
const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
return resolvedPath.length > 0 ? resolvedPath : null;
};
export const formatMissingToolsReason = (
report: ToolchainReport,
requiredRange: string | null,
): string | null => {
const nodeMissing = report.missingTools.includes("node");
const nodeOutOfRange =
!nodeMissing &&
requiredRange !== null &&
report.nodeVersion !== null &&
!satisfiesSemverRange(report.nodeVersion, requiredRange);
const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
return null;
}
const issues: string[] = [];
const remediations: string[] = [];
if (nodeMissing) {
issues.push("node");
remediations.push(
`Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
);
} else if (nodeOutOfRange) {
issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
remediations.push(
`a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
);
}
if (buildToolsMissing.length > 0) {
issues.push(...buildToolsMissing);
remediations.push(
"the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
);
}
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
};
const ensureNodePtyImpl = (
distro: string | null,
windowsRepoRoot: string,
windowsToWslPath: (
distro: string | null,
windowsPath: string,
) => Effect.Effect<Option.Option<string>>,
options: EnsureWslNodePtyOptions = {},
): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
if (Option.isNone(linuxRepoRootOption)) {
return {
ok: false,
reason: `wslpath conversion failed for ${windowsRepoRoot}`,
fatal: false,
} as const;
}
const linuxRepoRoot = linuxRepoRootOption.value;
// node-pty lives in the apps/server workspace's node_modules; resolve from
// there rather than the monorepo root, where Bun's hoist layout omits it.
const linuxServerDir = `${linuxRepoRoot}/apps/server`;
const probe = yield* runWslShell(
distro,
NODE_PTY_PROBE_SCRIPT(linuxServerDir),
PROBE_TIMEOUT,
options,
);
const nodePath = parseNodePath(probe.stdout);
const resolvedPath = parseResolvedPath(probe.stdout);
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
if (transportFailureReason !== null) {
return {
ok: false,
reason: transportFailureReason,
fatal: false,
} as const;
}
// No node at all, even after the shared resolver repaired PATH. Surface
// the specific, actionable toolchain message rather than a confusing
// node-pty error, and don't try to build.
if (nodePath === null) {
const toolchainCheck = yield* runWslShell(
distro,
TOOLCHAIN_CHECK_SCRIPT,
TOOLCHAIN_TIMEOUT,
options,
);
const toolchainTransportFailure = formatWslShellTransportFailureReason(
toolchainCheck.transportFailure,
);
if (toolchainTransportFailure !== null) {
return {
ok: false,
reason: toolchainTransportFailure,
fatal: false,
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
} as const;
}
const report = parseToolchainReport(toolchainCheck.stdout);
const reason =
formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
"Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
return { ok: false, reason, fatal: true } as const;
}
if (resolvedPath === null) {
return {
ok: false,
reason: "WSL login-shell PATH could not be resolved during backend preflight.",
fatal: true,
} as const;
}
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
// filesystem — a packaging regression, since the server bundle needs its
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
// Windows and dual mode surfaces the reason inline, instead of the server
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
if (probe.exitCode === 3) {
return {
ok: false,
reason:
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
fatal: true,
} as const;
}
if (probe.exitCode === 0) {
const rawVersion = parseNodeVersion(probe.stdout);
if (
rawVersion !== null &&
options.nodeEngineRange &&
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
) {
const range = options.nodeEngineRange.trim();
return {
ok: false,
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
fatal: true,
} as const;
}
return { ok: true, nodePath, resolvedPath } as const;
}
if (options.allowBuild !== true) {
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
if (packagedProbeFailure !== null) {
return {
ok: false,
reason: packagedProbeFailure,
fatal: true,
} as const;
}
}
// node is present but node-pty's native module didn't load.
const toolchainCheck = yield* runWslShell(
distro,
TOOLCHAIN_CHECK_SCRIPT,
TOOLCHAIN_TIMEOUT,
options,
);
const toolchainTransportFailure = formatWslShellTransportFailureReason(
toolchainCheck.transportFailure,
);
if (toolchainTransportFailure !== null) {
return {
ok: false,
reason: toolchainTransportFailure,
fatal: false,
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
} as const;
}
const report = parseToolchainReport(toolchainCheck.stdout);
if (options.allowBuild !== true) {
// Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
// or network is needed — and we must not nag the user to install build
// tools they don't need. Still surface a missing/too-old Node (both the
// prebuilt and the server require a compatible Node); otherwise reaching
// here means the bundled binary itself couldn't load, which is almost
// always an unsupported CPU architecture or incompatible system libraries.
const nodeOnlyReason = formatMissingToolsReason(
{
missingTools: report.missingTools.filter((tool) => tool === "node"),
nodeVersion: report.nodeVersion,
},
options.nodeEngineRange?.trim() || null,
);
return {
ok: false,
reason:
nodeOnlyReason ??
"The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
fatal: true,
} as const;
}
// Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
// source. Run the toolchain check first so a missing compiler or out-of-range
// Node surfaces a specific, actionable message instead of an opaque node-gyp
// failure. Developers have the toolchain; end users never reach this path.
const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
if (missingReason !== null) {
return { ok: false, reason: missingReason, fatal: true } as const;
}
const build = yield* runWslShell(
distro,
NODE_PTY_BUILD_SCRIPT(linuxServerDir),
BUILD_TIMEOUT,
options,
);
const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
if (buildTransportFailure !== null) {
return {
ok: false,
reason: buildTransportFailure,
fatal: false,
retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
} as const;
}
if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
return {
ok: false,
reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
fatal: true,
} as const;
});
export const probeWslDistros: Effect.Effect<
readonly WslDistro[],
DesktopWslDistroListError,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
});
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopWslDistroListError({
reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
});
}
return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
}),
).pipe(
Effect.mapError((error) =>
isDesktopWslDistroListError(error)
? error
: new DesktopWslDistroListError({
reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
}),
),
Effect.timeoutOption(LIST_TIMEOUT),
Effect.flatMap(
Option.match({
onNone: () =>
new DesktopWslDistroListError({
reason: "wsl.exe --list --verbose timed out",
}),
onSome: Effect.succeed,
}),
),
);
const preWarmImpl = (
distro: string | null,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
});
const handle = yield* spawner.spawn(command);
yield* handle.exitCode;
}),
).pipe(
Effect.timeoutOption(PRE_WARM_TIMEOUT),
Effect.asVoid,
Effect.catch(() => Effect.void),
);
const windowsToWslPathImpl = (
distro: string | null,
windowsPath: string,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
// wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
const normalized = windowsPath.replaceAll("\\", "/");
return Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
return converted.length > 0 ? Option.some(converted) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(WSLPATH_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
};
const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const getDistroIpImpl = (
distro: string | null,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
// `hostname -I` prints a space-separated list of all non-loopback
// IPs the distro has bound. The first entry on the WSL2 default
// network is always the eth0 vEthernet address Windows can reach
// directly (no wslhost forwarding required).
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
return candidate ? Option.some(candidate) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(USER_HOME_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
const getUserHomeImpl = (
distro: string | null,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(
"wsl.exe",
// printf so there's no trailing newline noise; getent so we get the
// real home from /etc/passwd even if $HOME is unset for some reason.
[
...buildDistroArgs(distro),
"--",
"sh",
"-c",
'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
return home.startsWith("/") ? Option.some(home) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(USER_HOME_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
const makeIsAvailable = (
platform: NodeJS.Platform,
windir: string,
): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
if (platform !== "win32") return false;
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const wslExePath = path.join(windir, "System32", "wsl.exe");
return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
});
export interface DesktopWslEnvironmentTestStub {
readonly isAvailable?: boolean;
readonly distros?: ReadonlyArray<WslDistro>;
readonly distroListError?: DesktopWslDistroListError;
readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
readonly getUserHome?: (distro: string | null) => Option.Option<string>;
readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
readonly ensureNodePty?: (
distro: string | null,
windowsRepoRoot: string,
options?: EnsureWslNodePtyOptions,
) => EnsureWslNodePtyResult;
}
export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
const probeDistros = stub.distroListError
? Effect.fail(stub.distroListError)
: Effect.succeed(stub.distros ?? []);
return Layer.succeed(
DesktopWslEnvironment,
DesktopWslEnvironment.of({
isAvailable: Effect.succeed(stub.isAvailable ?? false),
listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
probeDistros,
preWarm: () => Effect.void,
windowsToWslPath: (distro, windowsPath) =>
Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
ensureNodePty: (distro, windowsRepoRoot, options) =>
Effect.succeed(
stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
ok: false,
reason: "ensureNodePty stub not configured",
fatal: true,
},
),
}),
);
};
export const layer = Layer.effect(
DesktopWslEnvironment,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const windir = process.env.WINDIR ?? "C:\\Windows";
const provideSpawner = <A, E>(
effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
): Effect.Effect<A, E> =>
effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
// Probe wsl.exe once at layer init and cache the result, exposing
// `isAvailable` as a resolved value rather than a re-running effect.
// WSL availability is effectively static for the process lifetime — the
// Windows feature isn't added/removed mid-session, and backend mode
// changes already require an app restart — so the cached boolean stays
// accurate. Crucially this keeps `isAvailable` synchronously resolvable:
// it's read inside the sync IPC handler getLocalEnvironmentBootstraps
// (via the primary instance's lazy label -> resolvePrimaryLabel ->
// describePrimary). The underlying probe does a filesystem `exists`
// check, so leaving it as a live effect would make Effect.runSync throw
// there and break the renderer's synchronous bootstrap path.
const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, environment.path),
Effect.withSpan("desktop.wsl.isAvailable"),
);
const isAvailable = Effect.succeed(wslAvailable);
const windowsToWslPath = (distro: string | null, windowsPath: string) =>
provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
Effect.withSpan("desktop.wsl.windowsToWslPath"),
);
// Cache user-home results per distro key — folder picker can be opened
// many times in a session and the value is stable for the life of the
// distro. Negative results aren't cached so a transient wsl.exe failure
// doesn't permanently disable tilde expansion.
const userHomeCache = new Map<string, string>();
const getUserHome = (distro: string | null) =>
Effect.gen(function* () {
const key = distro ?? "__default__";
const cached = userHomeCache.get(key);
if (cached !== undefined) return Option.some(cached);
const resolved = yield* provideSpawner(getUserHomeImpl(distro));
if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
return resolved;
}).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
const getDistroIp = (distro: string | null) =>
provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
const probeDistros = provideSpawner(probeWslDistros).pipe(
Effect.withSpan("desktop.wsl.probeDistros"),
);
return DesktopWslEnvironment.of({
isAvailable,
listDistros: probeDistros.pipe(
Effect.orElseSucceed(() => []),
Effect.withSpan("desktop.wsl.listDistros"),
),
probeDistros,
preWarm: (distro) =>
provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
windowsToWslPath,
getUserHome,
getDistroIp,
ensureNodePty: (distro, windowsRepoRoot, options) =>
provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
Effect.withSpan("desktop.wsl.ensureNodePty"),
),
});
}),
);
+206
View File
@@ -0,0 +1,206 @@
import { describe, it, expect } from "vite-plus/test";
import {
DISTRO_NAME_PATTERN,
extractDistroFromUncPath,
isValidDistroName,
parseWslDistroList,
resolveWslHomeUncPath,
resolveWslPickFolderDefaultPath,
wslUncPathToLinuxPath,
} from "./wslPathParsing.ts";
function makeUtf16LeBuffer(text: string): Buffer {
return Buffer.from("" + text, "utf16le");
}
describe("parseWslDistroList", () => {
it("parses standard output with default distro marked", () => {
const output = makeUtf16LeBuffer(
[
" NAME STATE VERSION",
"* Ubuntu Running 2",
" Debian Stopped 2",
" Ubuntu-22.04 Running 1",
].join("\r\n"),
);
const distros = parseWslDistroList(output);
expect(distros).toEqual([
{ name: "Ubuntu", isDefault: true, version: 2 },
{ name: "Debian", isDefault: false, version: 2 },
{ name: "Ubuntu-22.04", isDefault: false, version: 1 },
]);
});
it("returns empty array for empty buffer", () => {
expect(parseWslDistroList(Buffer.alloc(0))).toEqual([]);
});
it("returns empty array for header-only output", () => {
const output = makeUtf16LeBuffer(" NAME STATE VERSION\r\n");
expect(parseWslDistroList(output)).toEqual([]);
});
it("skips malformed lines", () => {
const output = makeUtf16LeBuffer(
[
" NAME STATE VERSION",
"* Ubuntu Running 2",
" bad line",
"",
" Debian Stopped 2",
].join("\r\n"),
);
const distros = parseWslDistroList(output);
expect(distros).toEqual([
{ name: "Ubuntu", isDefault: true, version: 2 },
{ name: "Debian", isDefault: false, version: 2 },
]);
});
it("handles output without BOM", () => {
const text = [
" NAME STATE VERSION",
"* Ubuntu Running 2",
].join("\r\n");
const output = Buffer.from(text, "utf16le");
const distros = parseWslDistroList(output);
expect(distros).toEqual([{ name: "Ubuntu", isDefault: true, version: 2 }]);
});
it("handles UTF-8 output", () => {
const text = [
" NAME STATE VERSION",
"* Debian Running 2",
].join("\r\n");
const distros = parseWslDistroList(Buffer.from(text, "utf8"));
expect(distros).toEqual([{ name: "Debian", isDefault: true, version: 2 }]);
});
});
describe("extractDistroFromUncPath", () => {
it("extracts the distro from \\\\wsl.localhost UNC paths", () => {
expect(extractDistroFromUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh")).toBe(
"Ubuntu-22.04",
);
});
it("extracts the distro from the legacy \\\\wsl$ UNC paths", () => {
expect(extractDistroFromUncPath("\\\\wsl$\\Debian\\home\\josh")).toBe("Debian");
});
it("returns null for non-UNC Windows paths", () => {
expect(extractDistroFromUncPath("C:\\Users\\Josh\\project")).toBeNull();
});
it("returns null when the segment is not a valid distro name", () => {
expect(extractDistroFromUncPath("\\\\wsl.localhost\\bad name!\\home")).toBeNull();
});
});
describe("wslUncPathToLinuxPath", () => {
it("maps WSL UNC paths back to Linux absolute paths", () => {
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toBe(
"/home/josh/repo",
);
});
it("maps a distro UNC root to Linux root", () => {
expect(wslUncPathToLinuxPath("\\\\wsl$\\Debian")).toBe("/");
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/");
});
it("rejects invalid distro names and non-WSL paths", () => {
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull();
});
});
describe("resolveWslHomeUncPath", () => {
const distros = [
{ name: "Debian", isDefault: true, version: 2 as const },
{ name: "Ubuntu", isDefault: false, version: 2 as const },
];
it("uses the configured distro when one is selected", () => {
expect(resolveWslHomeUncPath({ distro: "Ubuntu" }, distros)).toBe(
"\\\\wsl.localhost\\Ubuntu\\home",
);
});
it("uses the actual default distro when config uses the WSL default", () => {
expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home",
);
});
it("omits the default path when no default distro is known", () => {
expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
});
});
describe("resolveWslPickFolderDefaultPath", () => {
const config = { distro: null };
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
it("uses WSL home when no initial path is provided", () => {
expect(resolveWslPickFolderDefaultPath(undefined, config, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home",
);
});
it("maps Linux initial paths to WSL UNC paths", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "/home/josh/project" }, config, distros),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
});
it("expands ~/path against the user's home dir when known", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros, "/home/josh"),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
});
it("resolves bare ~ to the user's home dir when known", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "~" }, config, distros, "/home/josh"),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh");
});
it("falls back to /home parent when the user's home dir isn't known", () => {
expect(resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home\\project",
);
});
it("preserves existing UNC initial paths", () => {
expect(
resolveWslPickFolderDefaultPath(
{ initialPath: "\\\\wsl.localhost\\Ubuntu\\home\\josh" },
config,
distros,
),
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\josh");
});
});
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
it("accepts common distro names", () => {
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
expect(isValidDistroName(name)).toBe(true);
}
});
it("rejects names with trailing whitespace, hyphen, or dot", () => {
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
}
});
it("rejects names containing control or shell-meta characters", () => {
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
}
});
});
+129
View File
@@ -0,0 +1,129 @@
export interface WslDistro {
readonly name: string;
readonly isDefault: boolean;
readonly version: 1 | 2;
}
export interface WslConfig {
readonly distro: string | null;
}
// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
const likelyUtf16Le =
hasUtf16Bom ||
Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
(byte, index) => index % 2 === 1 && byte === 0,
).length > 10;
let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
const distros: WslDistro[] = [];
for (let i = 1; i < lines.length; i++) {
const line = lines[i]!;
const isDefault = line.startsWith("*");
const cleaned = isDefault ? line.slice(1).trim() : line.trim();
const fields = cleaned.split(/\s{2,}/);
if (fields.length < 3) continue;
const name = fields[0]!.trim();
const versionNum = parseInt(fields[2]!, 10);
if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
distros.push({ name, isDefault, version: versionNum as 1 | 2 });
}
return distros;
}
// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\... so
// `wslpath` can be invoked inside the distro that actually owns the path,
// rather than whichever distro is configured for the desktop backend.
export function extractDistroFromUncPath(windowsPath: string): string | null {
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)/i.exec(windowsPath);
if (!match) return null;
const candidate = match[1]!;
return DISTRO_NAME_PATTERN.test(candidate) ? candidate : null;
}
export function wslUncPathToLinuxPath(windowsPath: string): string | null {
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath.trim());
if (!match) return null;
const distro = match[1]!;
if (!DISTRO_NAME_PATTERN.test(distro)) return null;
const rest = match[2] ?? "";
if (rest.length === 0) return "/";
return `/${rest.split("\\").filter(Boolean).join("/")}`;
}
export function resolveWslHomeUncPath(
config: WslConfig,
distros: readonly WslDistro[],
): string | null {
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
}
export function resolveWslPickFolderDefaultPath(
rawOptions: unknown,
config: WslConfig,
distros: readonly WslDistro[],
// Absolute Linux path of the user's home dir inside the chosen distro
// (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
// we don't open the picker at a non-existent `/home/<rest>`. When null we
// fall back to the `/home` parent — wrong directory but at least it exists.
userHome: string | null = null,
): string | null {
const homePath = resolveWslHomeUncPath(config, distros);
if (typeof rawOptions !== "object" || rawOptions === null) {
return homePath;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return homePath;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return homePath;
}
if (trimmedPath.startsWith("\\\\")) {
return trimmedPath;
}
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
if (!distroName) {
return homePath;
}
const toUncPath = (linuxPath: string) =>
`\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
if (trimmedPath === "~") {
return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
}
if (trimmedPath.startsWith("~/")) {
const remainder = trimmedPath.slice(2);
if (normalizedUserHome) {
return toUncPath(`${normalizedUserHome}/${remainder}`);
}
return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
}
if (trimmedPath.startsWith("/")) {
return toUncPath(trimmedPath);
}
return homePath;
}
export function isValidDistroName(value: string): boolean {
return DISTRO_NAME_PATTERN.test(value);
}
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^7.0.3"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

Before

Width:  |  Height:  |  Size: 649 B

After

Width:  |  Height:  |  Size: 665 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
<path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
<path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
</svg>

After

Width:  |  Height:  |  Size: 948 B

@@ -0,0 +1,414 @@
---
import Layout from "../layouts/Layout.astro";
interface Props {
readonly title: string;
readonly description: string;
readonly heading: string;
readonly lede: string;
readonly effectiveDate: string;
readonly lastUpdated: string;
readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
}
const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
---
<Layout title={title} description={description} pageClass="legal-document-page">
<div class="legal-page">
<a class="legal-index-link" href="/legal"><span aria-hidden="true">&#8592;</span> All legal documents</a>
<header class="legal-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>{heading}</h1>
<p class="legal-lede">{lede}</p>
<dl class="legal-dates" aria-label="Document dates">
<div>
<dt>Effective Date</dt>
<dd>{effectiveDate}</dd>
</div>
<div>
<dt>Last Updated</dt>
<dd>{lastUpdated}</dd>
</div>
</dl>
</header>
<div class="legal-rule" aria-hidden="true"></div>
<div class="legal-layout">
<aside class="legal-nav" aria-label="On this page">
<p class="legal-nav-label">On this page</p>
<ol>
{sections.map(([id, label], index) => (
<li>
<a href={`#${id}`} data-legal-nav-link={id}>
<span>{String(index + 1).padStart(2, "0")}</span>
{label}
</a>
</li>
))}
</ol>
</aside>
<article class="legal-copy">
<slot />
</article>
</div>
</div>
</Layout>
<script>
const navLinks = Array.from(
document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
);
const sections = navLinks
.map((link) => {
const id = link.dataset.legalNavLink;
const section = id ? document.getElementById(id) : null;
return section ? { link, section } : null;
})
.filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
let activeId = "";
let frame = 0;
const updateActiveSection = () => {
frame = 0;
const marker = Math.min(180, window.innerHeight * 0.28);
let active = sections[0];
for (const entry of sections) {
if (entry.section.getBoundingClientRect().top > marker) break;
active = entry;
}
if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
active = sections[sections.length - 1];
}
if (!active || active.section.id === activeId) return;
activeId = active.section.id;
for (const { link, section } of sections) {
if (section.id === activeId) {
link.setAttribute("aria-current", "location");
} else {
link.removeAttribute("aria-current");
}
}
};
const scheduleUpdate = () => {
if (frame) return;
frame = window.requestAnimationFrame(updateActiveSection);
};
updateActiveSection();
window.addEventListener("scroll", scheduleUpdate, { passive: true });
window.addEventListener("resize", scheduleUpdate);
</script>
<style is:global>
.legal-page {
width: min(1120px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-link {
display: none;
}
.legal-hero {
max-width: 820px;
animation: fade-in 0.8s ease-out both;
}
.legal-hero h1 {
margin-top: 18px;
font-size: clamp(3.4rem, 8vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.02em;
line-height: 0.9;
}
.legal-lede {
max-width: 720px;
margin-top: 34px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 1.8vw, 1.3rem);
line-height: 1.65;
letter-spacing: -0.012em;
}
.legal-dates {
display: flex;
flex-wrap: wrap;
gap: 36px;
margin-top: 38px;
}
.legal-dates div {
display: grid;
gap: 4px;
}
.legal-dates dt,
.legal-nav-label,
.section-number {
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.68rem;
font-weight: 500;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.legal-dates dd {
color: var(--fg);
font-family: var(--font-mono);
font-size: 0.8rem;
}
.legal-rule {
height: 1px;
margin: 72px 0;
background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
}
.legal-layout {
display: grid;
grid-template-columns: 210px minmax(0, 720px);
gap: clamp(64px, 10vw, 140px);
align-items: start;
}
.legal-nav {
position: sticky;
top: 88px;
max-height: calc(100vh - 112px);
overflow-y: auto;
scrollbar-width: thin;
}
.legal-nav ol {
display: grid;
gap: 2px;
margin-top: 16px;
padding-bottom: 12px;
list-style: none;
}
.legal-nav a {
display: grid;
grid-template-columns: 24px 1fr;
gap: 9px;
margin-left: -10px;
padding: 7px 8px 7px 10px;
border-radius: 6px;
color: var(--fg-dim);
font-size: 0.78rem;
line-height: 1.35;
transition:
color 0.16s ease,
background-color 0.16s ease,
box-shadow 0.16s ease;
}
.legal-nav a span {
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: 0.64rem;
line-height: 1.7;
}
.legal-nav a:hover {
color: var(--fg);
}
.legal-nav a[aria-current="location"] {
color: var(--fg);
background: color-mix(in srgb, var(--accent) 8%, transparent);
box-shadow: inset 2px 0 var(--accent);
}
.legal-nav a[aria-current="location"] span {
color: var(--accent);
}
.legal-copy {
min-width: 0;
}
.legal-copy section {
scroll-margin-top: 104px;
}
.legal-copy section + section {
margin-top: 82px;
padding-top: 82px;
border-top: 1px solid var(--border);
}
.section-number {
color: var(--accent);
}
.legal-copy h2 {
margin: 8px 0 28px;
color: var(--fg);
font-size: clamp(1.75rem, 3vw, 2.45rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 1.1;
}
.legal-copy h3 {
margin: 32px 0 10px;
color: var(--fg);
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.015em;
}
.legal-copy h4 {
margin: 24px 0 8px;
color: var(--fg);
font-size: 0.94rem;
font-weight: 600;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
color: var(--fg-muted);
font-size: 0.98rem;
font-style: normal;
line-height: 1.78;
}
.legal-copy p + p {
margin-top: 18px;
}
.legal-copy strong {
color: var(--fg);
font-weight: 600;
}
.legal-copy ul,
.legal-copy ol {
display: grid;
gap: 12px;
margin: 18px 0 20px;
padding-left: 1.2rem;
}
.legal-copy li {
padding-left: 7px;
}
.legal-copy li::marker {
color: var(--accent);
}
.legal-copy .provider-list {
gap: 28px;
}
.provider-list a,
.legal-copy a {
overflow-wrap: anywhere;
}
.legal-copy a {
color: var(--fg);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
text-underline-offset: 4px;
transition: text-decoration-color 0.16s ease;
}
.legal-copy a:hover {
text-decoration-color: var(--accent);
}
.legal-notice {
color: var(--fg) !important;
font-weight: 600;
}
.legal-copy address {
margin-top: 20px;
}
.contact-link {
display: inline-block;
margin-top: 18px;
font-family: var(--font-mono);
font-size: 0.9rem;
}
@media (max-width: 820px) {
.legal-index-link {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 38px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 0.72rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.legal-page {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.legal-hero h1 {
font-size: clamp(3.1rem, 16vw, 5rem);
}
.legal-rule {
margin: 52px 0;
}
.legal-layout {
display: block;
}
.legal-nav {
display: none;
}
.legal-copy section + section {
margin-top: 62px;
padding-top: 62px;
}
}
@media (max-width: 420px) {
.legal-page {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-lede {
margin-top: 26px;
font-size: 1rem;
}
.legal-dates {
gap: 24px;
}
.legal-copy p,
.legal-copy li,
.legal-copy address {
font-size: 0.94rem;
}
}
</style>
+31 -2
View File
@@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
pageClass?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The open-source control plane for coding agents.",
pageClass,
} = Astro.props;
---
@@ -30,7 +32,7 @@ const {
<title>{title}</title>
</head>
<body>
<div class="page">
<div class:list={["page", pageClass]}>
<nav class="nav">
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
@@ -67,6 +69,9 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
</div>
</div>
</footer>
@@ -279,7 +284,7 @@ const {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
overflow-x: clip;
}
.nav {
@@ -402,6 +407,8 @@ const {
.footer-links {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 20px;
}
@@ -421,6 +428,28 @@ const {
padding-left: 20px;
padding-right: 20px;
}
.legal-document-page .nav {
display: none;
}
.footer {
padding-bottom: max(32px, env(safe-area-inset-bottom));
}
.footer-inner {
align-items: flex-start;
flex-direction: column;
gap: 28px;
}
.footer-links {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
width: 100%;
gap: 14px 20px;
justify-content: initial;
}
}
@media (max-width: 420px) {
+1 -1
View File
@@ -1,6 +1,6 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
githubStars: "14k+",
users: "100,000",
} as const;
+44 -10
View File
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [
<span class="hero-float-mark hf-cursor" title="Cursor">
<img src="/harnesses/cursor_light.svg" alt="" />
</span>
<span class="hero-float-mark hf-grok" title="Grok">
<img src="/harnesses/grok-dark.svg" alt="" />
</span>
</div>
<div class="container hero-inner">
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [
</h1>
<p class="hero-sub">
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
Bring your own subscription. Fork the whole thing.
</p>
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [
<h2>Bring your own sub</h2>
<p>
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
or Cursor with the credentials you already have — we orchestrate
Cursor, or Grok with the credentials you already have — we orchestrate
them, you keep your plan.
</p>
</div>
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
<div class="harness-tag">cursor-agent</div>
</div>
</div>
<div class="harness">
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Grok CLI</div>
<div class="harness-tag">grok login</div>
</div>
</div>
</div>
<div class="harness-footer">
@@ -254,7 +264,7 @@ const mobileEndorsementRows = [
<button class="pr-button">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="6" r="2.2"/><path d="M6 8v8M18 8v5a3 3 0 01-3 3h-3M13 13l-2 3 2 3"/></svg>
Commit &amp; push
<span class="pr-button-kbd">⌘⏎</span>
<span id="pr-button-kbd" class="pr-button-kbd">⌘⏎</span>
</button>
</div>
</div>
@@ -403,12 +413,14 @@ const mobileEndorsementRows = [
const label = document.getElementById("download-label");
const ctaBtn = document.getElementById("cta-download-btn") as HTMLAnchorElement | null;
const ctaLabel = document.getElementById("cta-download-label");
const kbd = document.getElementById("pr-button-kbd");
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
if (label) label.textContent = platform.label;
if (ctaLabel) ctaLabel.textContent = platform.label;
if (kbd && platform.os !== "mac") kbd.textContent = "Ctrl ⏎";
try {
const release = await fetchLatestRelease();
@@ -613,8 +625,9 @@ const mobileEndorsementRows = [
.hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
.hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
.hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
.hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
@media (max-width: 1180px) {
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
@@ -623,6 +636,7 @@ const mobileEndorsementRows = [
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
}
@media (max-width: 820px) {
@@ -657,17 +671,18 @@ const mobileEndorsementRows = [
height: 44px;
}
/* Two above the title, two flanking the call-to-action area. */
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
.hero-float-mark.hf-claude {
top: 44px;
left: 10px;
transform: rotate(-10deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
.hero-float-mark.hf-grok {
top: 240px;
left: 4px;
right: auto;
transform: rotate(-4deg);
}
.hero-float-mark.hf-opencode {
@@ -677,6 +692,12 @@ const mobileEndorsementRows = [
transform: rotate(-6deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
}
.hero-float-mark.hf-cursor {
top: 474px;
right: 4px;
@@ -686,6 +707,14 @@ const mobileEndorsementRows = [
}
@media (max-width: 340px) {
.hero-float-mark.hf-grok {
top: 220px;
left: 0;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
@@ -702,6 +731,7 @@ const mobileEndorsementRows = [
right: 0;
}
.hero-float-mark.hf-grok img,
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
@@ -748,7 +778,7 @@ const mobileEndorsementRows = [
.harness-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(5, 1fr);
gap: 0;
border: 1px solid var(--border);
border-radius: var(--radius);
@@ -1203,6 +1233,10 @@ const mobileEndorsementRows = [
.harness-grid { grid-template-columns: 1fr 1fr; }
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
.harness:nth-child(5):last-child {
grid-column: 1 / -1;
border-right: 0;
}
.git-inner { grid-template-columns: 1fr; gap: 40px; }
.open-grid { grid-template-columns: 1fr; }
}
+172
View File
@@ -0,0 +1,172 @@
---
import Layout from "../layouts/Layout.astro";
const documents = [
{
number: "01",
title: "Privacy Policy",
description: "How T3 Code handles information, connected services, and your privacy choices.",
href: "/privacy-policy",
},
{
number: "02",
title: "Terms of Service",
description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
href: "/terms-of-service",
},
{
number: "03",
title: "Security Policy",
description: "Our security practices, responsible disclosure process, and shared responsibilities.",
href: "/security-policy",
},
] as const;
---
<Layout
title="Legal — T3 Code"
description="Privacy, terms, and security documents for T3 Code."
pageClass="legal-document-page"
>
<div class="legal-index">
<header class="legal-index-hero">
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
<h1>Legal</h1>
<p>Policies and terms for T3 Code, collected in one place.</p>
</header>
<nav class="document-list" aria-label="Legal documents">
{documents.map((document) => (
<a href={document.href} class="document-card">
<span class="document-number">{document.number}</span>
<span class="document-copy">
<strong>{document.title}</strong>
<span>{document.description}</span>
</span>
<span class="document-arrow" aria-hidden="true">&#8599;</span>
</a>
))}
</nav>
</div>
</Layout>
<style>
.legal-index {
width: min(960px, calc(100% - 64px));
margin: 0 auto;
padding: clamp(72px, 10vw, 132px) 0 112px;
}
.legal-index-hero {
max-width: 680px;
animation: fade-in 0.7s ease-out both;
}
.legal-index h1 {
margin-top: 18px;
font-size: clamp(4rem, 10vw, 7.4rem);
font-weight: 500;
letter-spacing: -0.04em;
line-height: 0.9;
}
.legal-index-hero > p:last-child {
margin-top: 30px;
color: var(--fg-muted);
font-size: clamp(1.05rem, 2vw, 1.3rem);
line-height: 1.65;
}
.document-list {
display: grid;
margin-top: clamp(64px, 9vw, 96px);
border-top: 1px solid var(--border);
}
.document-card {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) auto;
gap: 24px;
align-items: center;
padding: 30px 8px;
border-bottom: 1px solid var(--border);
transition: background-color 0.18s ease, padding 0.18s ease;
}
.document-number {
color: var(--accent);
font-family: var(--font-mono);
font-size: 0.7rem;
letter-spacing: 0.1em;
}
.document-copy {
display: grid;
gap: 7px;
}
.document-copy strong {
color: var(--fg);
font-size: 1.2rem;
font-weight: 500;
letter-spacing: -0.02em;
}
.document-copy > span {
color: var(--fg-dim);
font-size: 0.9rem;
line-height: 1.55;
}
.document-arrow {
color: var(--fg-dim);
font-size: 1.25rem;
transition: color 0.18s ease, transform 0.18s ease;
}
@media (hover: hover) and (pointer: fine) {
.document-card:hover {
padding-left: 16px;
padding-right: 16px;
background: rgba(255, 255, 255, 0.025);
}
.document-card:hover .document-arrow {
color: var(--fg);
transform: translate(2px, -2px);
}
}
@media (max-width: 820px) {
.legal-index {
width: min(100% - 40px, 720px);
padding-top: 56px;
padding-bottom: 80px;
}
.document-card {
grid-template-columns: 30px minmax(0, 1fr) auto;
gap: 14px;
padding: 24px 4px;
}
}
@media (max-width: 420px) {
.legal-index {
width: calc(100% - 32px);
padding-top: 42px;
}
.legal-index h1 {
font-size: 4.4rem;
}
.document-copy strong {
font-size: 1.08rem;
}
.document-copy > span {
font-size: 0.84rem;
}
}
</style>
@@ -0,0 +1,445 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["information", "Personal information we collect"],
["uses", "How we use your personal information"],
["sharing", "How we share your personal information"],
["choices", "Your choices regarding your personal information"],
["security", "Security of your personal information"],
["international", "International users"],
["children", "Children"],
["do-not-track", "Do Not Track"],
["updates", "Updates to this Privacy Policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Privacy Policy — T3 Code"
description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
heading="T3 Code Privacy Policy"
lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."
effectiveDate="2026-07-14"
lastUpdated="2026-07-14"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
Code desktop and mobile applications, the hosted T3 Code web application located at
{" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
service (together, the “Services”), or visit the T3 Code marketing website located at
{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
personal information we collect through the Site and the Services, as well as personal
information you provide to us directly.
</p>
<p>
By using the Site or the Services, you acknowledge the practices described in this
Policy. If you do not agree with this Policy, please do not use the Site or the Services.
This Policy does not govern third-party coding agents, artificial-intelligence providers,
identity providers, or environments that you choose to connect to T3 Code; those third
parties process information under their own terms and privacy policies.
</p>
</section>
<section id="information">
<p class="section-number">02</p>
<h2>Personal Information We Collect</h2>
<p>
We collect personal information about you in different ways depending on how you use
T3 Code and which optional features you enable.
</p>
<h3>Personal Information From Users of T3 Code</h3>
<p>
When you use T3 Code, we may collect the following categories of personal information:
</p>
<ul>
<li>
<strong>Account information.</strong> If you create or sign in to a T3 account, we
receive general identifiers and profile information from our authentication provider
and the identity provider you select. This may include your name, email address,
profile image, user ID, sign-in method, and authentication credentials or tokens.
</li>
<li>
<strong>Environment and device information.</strong> If you enable T3 Connect, we
process information needed to connect and secure your environments and devices,
including identifiers, labels you assign, public keys, connection endpoints,
credential hashes, connection status, app and operating-system versions, and
notification preferences.
</li>
<li>
<strong>Agent activity and notifications.</strong> If you enable notifications or Live
Activities, we process push tokens and limited activity information needed to provide
those features, such as project and thread titles, model name, status, and activity
headline.
</li>
<li>
<strong>Information you provide to us.</strong> We collect information that you choose
to provide when you request support, send feedback, or otherwise communicate with us.
</li>
</ul>
<h3>Personal Information From Users of Our Site Generally</h3>
<p>
When you visit the Site or use online portions of the Services, we and our service
providers may automatically log online identifiers and internet-activity information,
including your Internet Protocol (IP) address, device and operating-system type, browser
or app type and version, pages viewed, access times, request timestamps, connection
events, latency, error details, and diagnostic traces. The amount of information we
collect depends on the Services you use and your device and browser settings.
</p>
<p>
We use operational and diagnostic information to provide, secure, maintain, and
troubleshoot the Services, not for targeted advertising.
</p>
<h3>Information We Get From Others</h3>
<p>
We may receive personal information from service providers that help us operate the
Services, such as authentication and identity providers, app stores, device-platform
providers, and coding-agent providers you choose to use. We may combine this information
with information we collect through the Site and the Services.
</p>
<h3>Cookies and Local Storage</h3>
<p>
The Site and online portions of the Services may use cookies or similar technologies to
operate essential features, maintain sessions, remember preferences, and understand
whether the Services are functioning correctly. T3 Code also stores connection settings,
credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
your device. Credentials and session tokens use platform-provided protected storage where
supported. Information stored only on your device is not collected by T3 Tools unless it
is transmitted as part of a feature you use.
</p>
<h3>Device Permissions</h3>
<ul>
<li>
<strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
are processed on your device.
</li>
<li>
<strong>Photos and files.</strong> Items you select are accessed only to preview them or
attach them to a request you initiate.
</li>
<li>
<strong>Notifications.</strong> Used only if you enable agent-status notifications or
Live Activities.
</li>
<li>
<strong>Local network.</strong> Used to discover or connect to T3 Code environments
accessible from your machine over the network.
</li>
</ul>
</section>
<section id="uses">
<p class="section-number">03</p>
<h2>How We Use Your Personal Information</h2>
<p>
Subject to this Policy and applicable terms governing third-party applications and
services, we may use personal information for the following purposes:
</p>
<ul>
<li>To establish and verify your identity and authenticate your account;</li>
<li>To link and protect devices and environments and deliver optional notifications;</li>
<li>To process and fulfill requests you make through the Services;</li>
<li>To provide customer service and respond to support requests and feedback;</li>
<li>To communicate with you about the Services and your relationship with us;</li>
<li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
<li>To comply with applicable law and enforce the terms governing the Services; and</li>
<li>
To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
operational information.
</li>
</ul>
<h3>Training of AI Models</h3>
<p>
We do not use your personal information, source code, prompts, or agent responses to
train artificial-intelligence models.
</p>
<h3>Compliance and Protection</h3>
<p>We may use personal information to:</p>
<ul>
<li>Comply with applicable laws, lawful requests, and legal process;</li>
<li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
<li>Audit our internal processes for legal, contractual, and policy compliance;</li>
<li>Enforce the terms and conditions that govern the Site and the Services; and</li>
<li>
Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
unethical, or illegal activity, including cyberattacks and identity theft.
</li>
</ul>
<p>
We may also use personal information for other purposes consistent with this Policy or
explained to you when we collect the information.
</p>
</section>
<section id="sharing">
<p class="section-number">04</p>
<h2>How We Share Your Personal Information</h2>
<p>
We may disclose the categories of personal information described above to the following
categories of third parties:
</p>
<h3>Providers You Choose</h3>
<p>
At your direction, prompts, files, and related content are sent to coding agents and
artificial-intelligence providers configured in your environment. Because you bring and
configure your own coding-agent harness and provider, the applicable third parties vary.
Those providers process information under their own terms and privacy policies.
</p>
<h3>Third-Party Service Providers</h3>
<p>
We use third-party service providers to help provide the Services and operate our
business. Depending on the features you use, these providers may include:
</p>
<ul class="provider-list">
<li>
<strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
We use Clerk to provide account authentication.<br />
You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
>https://clerk.com/legal/privacy</a
>.
</li>
<li>
<strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
You can view Cloudflare's privacy policy here:{" "}<a
href="https://www.cloudflare.com/policies/privacy/"
>https://www.cloudflare.com/policies/privacy/</a
>.
</li>
<li>
<strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
We use PlanetScale to host the database that supports T3 Connect.<br />
You can view PlanetScale's privacy policy here:{" "}<a
href="https://planetscale.com/legal/privacy"
>https://planetscale.com/legal/privacy</a
>.
</li>
<li>
<strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
We use Vercel to host and deploy the T3 Code Site.<br />
You can view Vercel's privacy notice here:{" "}<a
href="https://vercel.com/legal/privacy-notice"
>https://vercel.com/legal/privacy-notice</a
>.
</li>
<li>
<strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
We use Axiom for operational diagnostics that help us maintain and troubleshoot the
Services.<br />
You can view Axiom's privacy policy here:{" "}<a
href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
>.
</li>
<li>
<strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
We use Expo for application updates and related mobile-app services.<br />
You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
>https://expo.dev/privacy</a
>.
</li>
<li>
<strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
We use Apple services for app distribution, optional authentication, and platform
notifications.<br />
You can view Apple's privacy policy here:{" "}<a
href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
>.
</li>
<li>
<strong>Google</strong> <em>(Google LLC)</em>.<br />
We use Google services for app distribution and optional authentication.<br />
You can view Google's privacy policy here:{" "}<a
href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
>.
</li>
</ul>
<p>
These providers process information for us under their own contractual and privacy
obligations.
</p>
<h3>Affiliates and Professional Advisors</h3>
<p>
We may share personal information with our affiliates for purposes consistent with this
Policy and with lawyers, accountants, bankers, and other professional advisors in the
course of the services they provide to us.
</p>
<h3>Corporate Restructuring</h3>
<p>
We may share some or all personal information in connection with or during negotiation of
a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
assets, or similar transaction. If another company acquires T3 Tools or its assets, that
company may possess the personal information collected by us and assume the rights and
obligations described in this Policy.
</p>
<h3>Legal and Safety Disclosures</h3>
<p>
We may disclose personal information if we believe in good faith that disclosure is
necessary to comply with law or legal process; protect or defend the rights, property, or
safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
Services. We may also share personal information at your direction, with your consent, or
as described to you when the information is collected.
</p>
<h3>No Sale of Personal Information</h3>
<p>
We do not sell your personal information or share it for cross-context behavioral or
targeted advertising.
</p>
<h3>Third-Party Websites and Services</h3>
<p>
The Site and the Services may contain links to third-party websites or services. When you
follow a third-party link or connect a third-party service, that third party may collect
personal information from you. We do not control and are not responsible for the privacy
practices or content of third parties.
</p>
</section>
<section id="choices">
<p class="section-number">05</p>
<h2>Your Choices Regarding Your Personal Information</h2>
<h3>Account and Connection Choices</h3>
<p>
You may use local or direct connections without signing in to a T3 account. You can
disconnect environments, sign out, disable optional notifications and Live Activities,
and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
and notification permissions in your device settings.
</p>
<h3>Cookies and Local Data</h3>
<p>
You can use your browser settings to stop accepting or to delete cookies, although some
portions of the Site or the Services may not function correctly as a result. Information
stored only on your device remains there until you clear it, remove the relevant
connection, or uninstall the app. The mobile app provides cache controls under
{" "}<strong>Settings → App → Client Storage</strong>.
</p>
<h3>Retention and Deletion</h3>
<p>
We retain account, environment-link, device-registration, notification, and security
information while your account or the relevant feature is active and for as long as
reasonably necessary to provide the Services, protect them from abuse, comply with law,
and resolve disputes. Operational diagnostic traces are configured to expire after 30
days. Some records may remain longer in backups or where retention is required for
security, fraud prevention, or legal compliance.
</p>
<p>
To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
href="mailto:[email protected]">[email protected]</a
>{" "}from the email address associated with your account. We may need to verify your
identity. Deleting a T3 account does not delete information held by an environment or
coding-agent provider you control; contact those providers or delete that information
directly.
</p>
<h3>Your Privacy Rights</h3>
<p>
Depending on where you live, you may have rights to request access to, correction of,
deletion of, or a portable copy of your personal information, or to restrict or object
to certain processing. You may also have the right to appeal our response or complain to
a data-protection authority. We will honor applicable rights after verifying your
request.
</p>
</section>
<section id="security">
<p class="section-number">06</p>
<h2>Security of Your Personal Information</h2>
<p>
T3 Tools is committed to protecting the security of your personal information. We use
administrative, technical, and organizational safeguards designed to protect personal
information from unauthorized access, use, or disclosure. These safeguards include
encrypted network transport, scoped and proof-bound access tokens for supported
connection flows, protected credential storage, and redaction of authorization headers
from relay diagnostics.
</p>
<p>
No method of transmission over the Internet or method of electronic storage is completely
secure. While we use reasonable efforts to protect personal information, we cannot
guarantee its absolute security. You are responsible for securing the environments,
coding-agent accounts, credentials, and networks that you connect to T3 Code.
</p>
</section>
<section id="international">
<p class="section-number">07</p>
<h2>International Users</h2>
<p>
The Site and the Services are provided from the United States and are governed by United
States law. If you use the Site or the Services from outside the United States, your
personal information may be transferred to and processed in the United States and other
countries where we or our service providers operate. Where required, we use lawful
safeguards for international transfers of personal information.
</p>
</section>
<section id="children">
<p class="section-number">08</p>
<h2>Children</h2>
<p>
The Site and the Services are not intended for children under 13 years of age, and you
must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
personal information from children under 13. If you believe a child under 13 has provided
us with personal information, please contact us so that we can take appropriate action.
</p>
</section>
<section id="do-not-track">
<p class="section-number">09</p>
<h2>Do Not Track</h2>
<p>
We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
personal information for cross-context behavioral or targeted advertising.
</p>
</section>
<section id="updates">
<p class="section-number">10</p>
<h2>Updates to This Privacy Policy</h2>
<p>
We reserve the right to update this Policy from time to time. If we make material changes,
we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
above, and provide any additional notice required by law. Except as otherwise indicated,
changes become effective when the revised Policy is posted.
</p>
</section>
<section id="contact">
<p class="section-number">11</p>
<h2>Contact Us</h2>
<p>
If you have questions about this Policy or wish to make a privacy or deletion request,
please contact us at:
</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
@@ -0,0 +1,187 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["reporting", "Reporting security issues"],
["safe-harbor", "Responsible research and safe harbor"],
["practices", "Our security practices"],
["responsibilities", "Your responsibilities"],
["updates", "Updates to this policy"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Security Policy — T3 Code"
description="How to report security issues in T3 Code and how T3 Tools approaches product security."
heading="T3 Code Security Policy"
lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
This Security Policy describes the vulnerability-reporting process and security practices for
the T3 Code desktop and mobile applications, the hosted application at{" "}<a
href="https://app.t3.codes">https://app.t3.codes</a
>, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
>https://t3.codes</a
>.
</p>
<p>
T3 Code connects software running on your devices and in environments you control with
coding-agent harnesses and providers you choose. We secure the software and infrastructure
operated by T3 Tools, but we do not control the security of your devices, environments,
repositories, networks, credentials, or third-party providers. Please review the shared
responsibilities below when assessing risk.
</p>
</section>
<section id="reporting">
<p class="section-number">02</p>
<h2>Reporting Security Issues</h2>
<p>
If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not
disclose the issue publicly until we have had a reasonable opportunity to investigate and
remediate it.
</p>
<p>Please include, when available:</p>
<ul>
<li>A description of the issue and its potential impact;</li>
<li>The affected application, version, URL, endpoint, or component;</li>
<li>Clear reproduction steps or a minimal proof of concept;</li>
<li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
<li>Your preferred contact information and whether you want public credit.</li>
</ul>
<p>
We aim to acknowledge complete reports within one business day, keep reporters informed of
material progress, and coordinate disclosure after a fix is available. Resolution time varies
with severity, complexity, and dependencies on third parties.
</p>
</section>
<section id="safe-harbor">
<p class="section-number">03</p>
<h2>Responsible Research and Safe Harbor</h2>
<p>
We support good-faith security research. If you make a genuine effort to comply with this
policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
as authorized and will not initiate legal action against you for accidental, good-faith
violations of this policy. If a third party initiates legal action concerning compliant
research, we will make our authorization known where appropriate.
</p>
<p>To remain within this safe harbor, you must:</p>
<ul>
<li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
<li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
<li>Access only the minimum information needed to demonstrate the issue;</li>
<li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
<li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
<li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
<li>Give us reasonable time to address the issue before public disclosure.</li>
</ul>
<p>
This safe harbor does not authorize violations of law or activity outside the scope of this
policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
in its discretion.
</p>
</section>
<section id="practices">
<p class="section-number">04</p>
<h2>Our Security Practices</h2>
<p>
We use administrative, technical, and organizational safeguards designed for the nature of T3
Code and the information processed by T3 Tools-operated services. These practices include:
</p>
<ul>
<li>
<strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
between your clients, your environment, and the harnesses and providers you configure. We
process information through T3 Tools-operated infrastructure only when needed for a feature
you enable.
</li>
<li>
<strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
transport. Supported connection flows use scoped credentials and security controls designed
to reduce unauthorized reuse.
</li>
<li>
<strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
credentials and session tokens where supported. We design operational logging to avoid
collecting secrets that are not needed to operate or troubleshoot the Services.
</li>
<li>
<strong>Access controls.</strong> Access to production systems and operational data is limited
according to job responsibilities and protected using authentication and authorization
controls.
</li>
<li>
<strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
reliability and security events, review dependencies, and deploy updates and mitigations as
appropriate.
</li>
<li>
<strong>Established providers.</strong> We use specialized providers for services such as
authentication, hosting, and application distribution and evaluate the controls relevant to
their role.
</li>
</ul>
<p>
No system is completely secure. These practices reduce risk but do not guarantee that the Site
or Services will be free from vulnerabilities or unauthorized access.
</p>
</section>
<section id="responsibilities">
<p class="section-number">05</p>
<h2>Your Responsibilities</h2>
<p>
Because you control much of the T3 Code execution path, you play an important role in securing
it. You are responsible for:
</p>
<ul>
<li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
<li>Securing your devices, repositories, environments, networks, and backups;</li>
<li>Protecting account, provider, repository, and environment credentials;</li>
<li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
<li>Granting providers and integrations only the permissions they need;</li>
<li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
<li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
<li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
</ul>
<p>
Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
Revoke any secret that may have been exposed before sharing sanitized evidence with us.
</p>
</section>
<section id="updates">
<p class="section-number">06</p>
<h2>Updates to This Policy</h2>
<p>
We may update this Security Policy as T3 Code, our infrastructure, and security practices
evolve. We will post revisions at this URL and update the dates above. Material changes to the
vulnerability-reporting process or safe-harbor terms will apply prospectively.
</p>
</section>
<section id="contact">
<p class="section-number">07</p>
<h2>Contact Us</h2>
<p>
Report security issues or ask security-related questions at{" "}<a
href="mailto:[email protected]">[email protected]</a
>.
</p>
<p>
For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
</p>
</section>
</LegalPage>
@@ -0,0 +1,396 @@
---
import LegalPage from "../components/LegalPage.astro";
const sections = [
["introduction", "Introduction"],
["accounts", "Accounts"],
["content", "Your content and providers"],
["rights", "T3 Code and proprietary rights"],
["acceptable-use", "Acceptable use"],
["availability", "Availability and changes"],
["fees", "Fees"],
["privacy", "Privacy"],
["termination", "Suspension and termination"],
["beta", "Beta services"],
["disclaimers", "Disclaimers"],
["liability", "Limitation of liability"],
["indemnification", "Indemnification"],
["copyright", "Copyright complaints"],
["third-parties", "Third-party services"],
["feedback", "Feedback"],
["disputes", "Dispute resolution"],
["miscellaneous", "Miscellaneous"],
["changes", "Changes to these Terms"],
["contact", "Contact us"],
] as const;
---
<LegalPage
title="Terms of Service — T3 Code"
description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
heading="T3 Code Terms of Service"
lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."
effectiveDate="2026-07-15"
lastUpdated="2026-07-15"
sections={sections}
>
<section id="introduction">
<p class="section-number">01</p>
<h2>Introduction</h2>
<p>
These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
(“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
>https://app.t3.codes</a
>, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
</p>
<p>
By accessing or using the Site or Services, you agree to these Terms. If you use the Services
for an organization, you represent that you have authority to bind that organization, and
“you” includes the organization. If you do not agree to these Terms, do not use the Site or
Services.
</p>
<p>
You must be at least 13 years old to use the Site or Services. If the law where you live
requires a greater age to enter into these Terms, you must meet that requirement or have a
parent or legal guardian agree on your behalf.
</p>
</section>
<section id="accounts">
<p class="section-number">02</p>
<h2>Accounts</h2>
<p>
You can use some T3 Code features without creating a T3 account. An account may be required
for account-backed features, including T3 Connect. You agree to provide accurate account
information, keep your credentials secure, and promptly notify us if you suspect unauthorized
access. You are responsible for activity performed through your account and connected devices,
except to the extent caused by our failure to use reasonable security measures.
</p>
<p>
You may not share credentials in a way that compromises the Services, impersonate another
person, or create accounts through unauthorized automated means. We may require reasonable
verification before restoring access or acting on an account request.
</p>
</section>
<section id="content">
<p class="section-number">03</p>
<h2>Your Content and Providers</h2>
<p>
T3 Code can help you send prompts, source files, images, attachments, review comments, and
instructions to coding-agent harnesses and providers you choose, and display their responses,
command output, file changes, source code, and diffs (collectively, “User Content”). You retain
all rights you have in your User Content.
</p>
<p>
You bring and configure your own coding-agent harness and provider. Your User Content is
ordinarily processed in the environment you control and by the providers you select, not by
T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
process that content only as reasonably necessary to provide, secure, and troubleshoot that
feature. This license ends when the content is no longer needed for those purposes, subject to
reasonable backup, security, and legal-retention requirements.
</p>
<p>
You represent that you have the rights and permissions needed to use and submit User Content
and to direct its processing by your selected harnesses and providers. You are responsible for
reviewing those providers’ terms, privacy practices, data controls, and output before using
them with confidential, proprietary, regulated, or personal information.
</p>
</section>
<section id="rights">
<p class="section-number">04</p>
<h2>T3 Code and Proprietary Rights</h2>
<p>
T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
infrastructure, documentation, and other materials, excluding User Content and third-party
materials. These Terms do not transfer ownership of either party’s intellectual property.
</p>
<p>
Portions of T3 Code are available as open-source software. Your use, copying, modification, and
distribution of that source code are governed by the license included with the applicable
repository or component. These Terms govern your use of the hosted Services and do not limit
rights granted to you by an applicable open-source license.
</p>
<p>
Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
to access and use the Services for lawful personal or internal business purposes. You may not
use our trademarks, service marks, or trade dress without written permission.
</p>
</section>
<section id="acceptable-use">
<p class="section-number">05</p>
<h2>Acceptable Use</h2>
<p>You may not use the Site or Services to:</p>
<ul>
<li>Violate applicable law or another person’s rights;</li>
<li>Upload, transmit, or generate content you do not have the right to use;</li>
<li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
<li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
<li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
<li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
<li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
<li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
</ul>
<p>
Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
We may investigate suspected violations and take proportionate action to protect users and the
Services.
</p>
</section>
<section id="availability">
<p class="section-number">06</p>
<h2>Availability and Changes</h2>
<p>
We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
aim to provide reasonable notice when a change materially reduces an account-backed feature,
but urgent security, legal, or reliability changes may take effect immediately. The Services
may be unavailable because of maintenance, provider outages, network conditions, or events
outside our control.
</p>
<p>
T3 Code depends on software, environments, networks, and coding-agent providers that you
configure or that third parties operate. We do not control their availability, compatibility,
pricing, or behavior.
</p>
</section>
<section id="fees">
<p class="section-number">07</p>
<h2>Fees</h2>
<p>
T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
otherwise for a feature. You remain responsible for charges from your coding-agent providers,
cloud infrastructure, network operators, app stores, and other third parties. If we introduce
a paid feature, we will present its price and applicable payment terms before you purchase it.
</p>
</section>
<section id="privacy">
<p class="section-number">08</p>
<h2>Privacy</h2>
<p>
Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
shares personal information when you use the Site and Services. Third-party environments,
harnesses, identity providers, and coding-agent providers process information under their own
terms and privacy policies.
</p>
</section>
<section id="termination">
<p class="section-number">09</p>
<h2>Suspension and Termination</h2>
<p>
You may stop using the Services at any time. You may disconnect environments and devices from
within T3 Code and may request deletion of an account as described in our Privacy Policy.
</p>
<p>
We may suspend or terminate access to account-backed or hosted features if we reasonably
believe you materially violated these Terms, created a security or legal risk, failed to pay an
applicable fee, or used the Services in a way that could harm other users or shared
infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
immediately where needed to prevent harm or comply with law.
</p>
<p>
Provisions that by their nature should survive termination—including ownership, disclaimers,
limitations of liability, indemnification, and dispute terms—will survive.
</p>
</section>
<section id="beta">
<p class="section-number">10</p>
<h2>Beta Services</h2>
<p>
T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
copy of important work, and review proposed commands and file changes before applying them.
</p>
</section>
<section id="disclaimers">
<p class="section-number">11</p>
<h2>Disclaimers</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
</p>
<p>
Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
or harmful output. You are responsible for reviewing output, commands, patches, and other
actions before relying on or executing them. We do not warrant that the Services or third-party
output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
</p>
<p>
Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
apply to you.
</p>
</section>
<section id="liability">
<p class="section-number">12</p>
<h2>Limitation of Liability</h2>
<p class="legal-notice">
TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
</p>
<p>
To the maximum extent permitted by law, our aggregate liability for all claims arising from or
relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
of its essential purpose. They do not limit liability that cannot lawfully be limited.
</p>
</section>
<section id="indemnification">
<p class="section-number">13</p>
<h2>Indemnification</h2>
<p>
To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
affiliates, officers, employees, and agents from third-party claims, damages, losses, and
reasonable legal fees arising from your User Content, your use of the Site or Services in
violation of these Terms or law, or your infringement of another person’s rights. We will
promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
settle a claim in a way that admits fault by or imposes obligations on us without our written
consent.
</p>
</section>
<section id="copyright">
<p class="section-number">14</p>
<h2>Copyright Complaints</h2>
<p>
If you believe material available through a T3 Tools-operated part of the Site or Services
infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a
>{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
contact information, a statement of good-faith belief, a statement under penalty of perjury
that the notice is accurate and you are authorized to act, and your physical or electronic
signature.
</p>
<p>
T3 Tools does not control content stored only in a user’s environment or held by a user-selected
provider. Requests concerning that material should be directed to the operator that hosts it.
</p>
</section>
<section id="third-parties">
<p class="section-number">15</p>
<h2>Third-Party Services</h2>
<p>
The Services may connect to or display content from third-party coding agents, model providers,
identity providers, repositories, app stores, websites, and infrastructure. Your use of those
services is governed by their terms. We do not endorse or control third-party services and are
not responsible for their content, security, availability, output, or data practices.
</p>
<p>
Third-party and open-source software included with T3 Code is governed by its applicable
license notices. Where those licenses conflict with these Terms for that software, the
applicable open-source license controls.
</p>
</section>
<section id="feedback">
<p class="section-number">16</p>
<h2>Feedback</h2>
<p>
If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
without restriction or compensation. This does not transfer ownership of your User Content.
</p>
</section>
<section id="disputes">
<p class="section-number">17</p>
<h2>Dispute Resolution</h2>
<p class="legal-notice">
PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
</p>
<h3>Informal Resolution</h3>
<p>
Before starting arbitration or a court proceeding, the party raising a dispute must send a
written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
href="mailto:[email protected]">[email protected]</a
>. The parties will try in good faith to resolve the dispute for at least 30 days.
</p>
<h3>Binding Arbitration</h3>
<p>
Except for disputes eligible for small-claims court and requests for injunctive relief to
protect intellectual property or prevent unauthorized access, unresolved disputes will be
resolved by binding individual arbitration administered by JAMS under its applicable consumer
or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
take place remotely unless the arbitrator determines that an in-person hearing is necessary.
</p>
<h3>No Class Actions</h3>
<p>
Disputes must be brought only on an individual basis. Neither party may participate in a class,
collective, consolidated, or representative action or arbitration to the extent permitted by
law.
</p>
<h3>Opt Out</h3>
<p>
You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"
>[email protected]</a
> within 30 days after you first accept these Terms. Include your name, the email associated
with your account if any, and a clear statement that you opt out of arbitration.
</p>
<p>
If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
state and federal courts located in San Francisco County, California, and each party consents
to those courts.
</p>
</section>
<section id="miscellaneous">
<p class="section-number">18</p>
<h2>Miscellaneous</h2>
<p>
California law governs these Terms without regard to conflict-of-law principles, except that
the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
incorporated by reference are the entire agreement between you and us regarding the Site and
Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
or severed, and the remaining provisions will continue in effect.
</p>
<p>
Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
written consent. We may assign them in connection with a merger, acquisition, reorganization,
or sale of assets. We are not liable for delays or failures caused by events beyond our
reasonable control. Headings are for convenience only, and “including” means “including without
limitation.”
</p>
</section>
<section id="changes">
<p class="section-number">19</p>
<h2>Changes to These Terms</h2>
<p>
We may update these Terms from time to time. We will post updated Terms at this URL and update
the dates above. If a change materially affects your rights, we will provide additional notice
when reasonably practicable or as required by law. Changes apply prospectively from their
effective date. Your continued use of the Site or Services after that date means you accept the
updated Terms.
</p>
</section>
<section id="contact">
<p class="section-number">20</p>
<h2>Contact Us</h2>
<p>If you have questions about these Terms, contact us at:</p>
<address>
<strong>T3 Tools, Inc.</strong><br />
2261 Market Street #5309<br />
San Francisco, CA 94114<br />
United States
</address>
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
</section>
</LegalPage>
Loaded 100 of 1183 files, more files were not shown because too many files have changed in this diff. Show more