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
Julius Marmingeandcodex cebbe6ff19 [codex] Preserve child process termination context (#3469)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:04 -07:00
Julius Marmingeandcodex e4a84a348e [codex] Structure release output failures (#3470)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:01 -07:00
Julius Marmingeandcodex 61e6d89d69 [codex] Structure GitHub CLI failures (#3456)
Co-authored-by: codex <[email protected]>
2026-06-20 19:14:35 -07:00
Julius Marmingeandcodex 1b2f39d018 [codex] Structure theme synchronization failures (#3466)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:05 -07:00
Julius Marmingeandcodex 8c2d33abde [codex] Structure release package updater failures (#3468)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:02 -07:00
Julius Marmingeandcodex 60dc4af916 [codex] Structure desktop build script failures (#3452)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:22 -07:00
Julius Marmingeandcodex d389cfd4e3 [codex] Structure Azure DevOps CLI failures (#3460)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:19 -07:00
Julius Marmingeandcodex 6fc79737c3 [codex] Structure mobile native static-check failures (#3464)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:16 -07:00
Julius Marmingeandcodex cdd03591ef [codex] Structure release metadata failures (#3467)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:13 -07:00
Julius Marmingeandcodex 2fbb0565d7 [codex] Structure workspace search cleanup failures (#3465)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:08 -07:00
Julius Marmingeandcodex a3dadc04bf [codex] Structure Bitbucket API errors (#3457)
Co-authored-by: codex <[email protected]>
2026-06-20 18:47:12 -07:00
Julius Marmingeandcodex 1a59277dc8 [codex] Structure GitLab CLI failures (#3458)
Co-authored-by: codex <[email protected]>
2026-06-20 18:41:25 -07:00
Julius Marmingeandcodex 6424197a19 [codex] Structure unroutable app-server messages (#3463)
Co-authored-by: codex <[email protected]>
2026-06-20 18:30:19 -07:00
Julius Marmingeandcodex 8d4a8b4f31 [codex] Structure preview capability errors (#3454)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:12 -07:00
Julius Marmingeandcodex 23ab75e84a [codex] Split project command failures (#3459)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:07 -07:00
Julius Marmingeandcodex 0488e47d9c [codex] Structure checkpoint diff failures (#3453)
Co-authored-by: codex <[email protected]>
2026-06-20 18:07:22 -07:00
Julius Marmingeandcodex 0eba548282 [codex] Model asset access failures with distinct errors (#3448)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:07 -07:00
Julius Marmingeandcodex 68c0dd3b70 [codex] Structure server CLI failures (#3450)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:02 -07:00
Julius Marmingeandcodex 4cd958445f [codex] Migrate desktop app errors to Schema (#3449)
Co-authored-by: codex <[email protected]>
2026-06-20 17:25:27 -07:00
Julius Marmingeandcodex 9f7861aadd [codex] Structure desktop update persistence errors (#3261)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:17 -07:00
Julius Marmingeandcodex 9243ead1c3 [codex] Preserve Linux icon resize fallback failures (#3447)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:11 -07:00
Julius Marmingeandcodex 803c2b7738 [codex] Preserve desktop backend output read failures (#3444)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:21 -07:00
Julius Marmingeandcodex 28e7c9ae17 [codex] Structure mobile waitlist enrollment failures (#3446)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:15 -07:00
Julius Marmingeandcodex a9460bb772 [codex] Structure pull request link failures (#3445)
Co-authored-by: codex <[email protected]>
2026-06-20 16:44:22 -07:00
Julius Marmingeandcodex 5edf7c56ba [codex] Preserve PR materialization failure chains (#3443)
Co-authored-by: codex <[email protected]>
2026-06-20 16:38:56 -07:00
Julius Marmingeandcodex 90dc76b11e Preserve asset access failure causes (#3342)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:22 -07:00
Julius Marmingeandcodex 57d25c934b [codex] Structure persistence error correlation (#3439)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:16 -07:00
Julius Marmingeandcodex a26f0dc89f [codex] structure source-control repository failures (#3336)
Co-authored-by: codex <[email protected]>
2026-06-20 15:56:46 -07:00
Julius Marmingeandcodex 6ff6c13fc8 [codex] structure desktop backend process errors (#3254)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:50 -07:00
Julius Marmingeandcodex 60c9ca0e33 [codex] Preserve checkpoint repository detection failures (#3360)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:44 -07:00
Julius Marmingeandcodex ad2cb1dd57 [codex] Diagnose desktop client settings read failures (#3432)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:38 -07:00
Julius Marmingeandcodex 674590e009 [codex] Fix terminal cwd error test construction (#3440)
Co-authored-by: codex <[email protected]>
2026-06-20 15:47:58 -07:00
Julius Marmingeandcodex f2cb14e774 [codex] Structure mobile relay token-store failures (#3309)
Co-authored-by: codex <[email protected]>
2026-06-20 15:31:33 -07:00
Julius Marmingeandcodex e042c25f56 [codex] Structure rotating log sink errors (#3279)
Co-authored-by: codex <[email protected]>
2026-06-20 15:24:38 -07:00
Julius Marmingeandcodex 90f1936fad [codex] Structure server runtime-state failures (#3319)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:05 -07:00
Julius Marmingeandcodex 42ff43915a [codex] Preserve mobile review highlighter failures (#3337)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:00 -07:00
Julius Marmingeandcodex 834e5db458 [codex] structure project CLI failures (#3339)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:55 -07:00
Julius Marmingeandcodex 8ce627ba91 [codex] Structure mobile thread outbox failures (#3341)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:51 -07:00
Julius Marmingeandcodex 9a78c6f2ba [codex] Structure web local storage failures (#3350)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:46 -07:00
Julius Marmingeandcodex aab72f10c1 [codex] Report markdown interaction failures (#3355)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:41 -07:00
Julius Marmingeandcodex a76b7bbfb5 Preserve PortScanner probe defects (#3282)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:02 -07:00
Julius Marmingeandcodex a51691a9b0 [codex] Structure server environment-label probe failures (#3321)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:53 -07:00
Julius Marmingeandcodex 97de7d7e15 [codex] Structure agent awareness registration errors (#3328)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:48 -07:00
Julius Marmingeandcodex d7718e81e0 [codex] Structure mobile notification navigation failures (#3359)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:04 -07:00
Julius Marmingeandcodex b88873508e [codex] Structure cross-client clipboard failures (#3361)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:59 -07:00
Julius Marmingeandcodex 58053d146b [codex] Structure terminal PTY operation failures (#3364)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:54 -07:00
Julius Marmingeandcodex 50767683b3 [codex] Preserve terminal preview link failure context (#3367)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:50 -07:00
Julius Marmingeandcodex d1339f3846 [codex] Structure client state key errors (#3374)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:45 -07:00
Julius Marmingeandcodex faccdd4ca9 [codex] Preserve desktop backend log failures (#3375)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:40 -07:00
Julius Marmingeandcodex dd48bfd98c [codex] Structure server settings failures (#3376)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:36 -07:00
Julius Marmingeandcodex 6d8d995621 [codex] Correlate protocol request failures (#3433)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:31 -07:00
Julius Marmingeandcodex b6c590af38 [codex] Fix desktop preview event delivery errors (#3435)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:27 -07:00
Julius Marmingeandcodex b51aef10c4 [codex] Preserve cloud disconnect diagnostics (#3437)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:22 -07:00
Julius Marmingeandcodex fc2cdeceb9 [codex] Structure preview automation boundary failures (#3436)
Co-authored-by: codex <[email protected]>
2026-06-20 13:50:19 -07:00
Julius Marmingeandcodex c637dfc454 [codex] enrich Git workflow errors (#3241)
Co-authored-by: codex <[email protected]>
2026-06-20 13:16:32 -07:00
Julius Marmingeandcodex 6e9b43cb84 Preserve trace file read causes (#3300)
Co-authored-by: codex <[email protected]>
2026-06-20 13:11:52 -07:00
Julius Marmingeandcodex be56fa43b0 [codex] Preserve workspace root stat failures (#3278)
Co-authored-by: codex <[email protected]>
2026-06-20 12:58:59 -07:00
Julius Marmingeandcodex eb5eb0d9fa [codex] Structure managed endpoint allocation failures (#3421)
Co-authored-by: codex <[email protected]>
2026-06-20 12:58:10 -07:00
Julius Marmingeandcodex 621616268a [codex] Sanitize text generation CLI errors (#3431)
Co-authored-by: codex <[email protected]>
2026-06-20 12:33:22 -07:00
Julius Marmingeandcodex 630df6b986 [codex] Enrich source-control errors (#3248)
Co-authored-by: codex <[email protected]>
2026-06-20 12:32:34 -07:00
Julius Marmingeandcodex 569b3e5959 [codex] Structure desktop SSH prompt presentation failures (#3429)
Co-authored-by: codex <[email protected]>
2026-06-20 12:31:49 -07:00
Julius Marmingeandcodex d7ff7e7333 [codex] Audit managed endpoint error context (#3245)
Co-authored-by: codex <[email protected]>
2026-06-20 12:30:03 -07:00
Julius Marmingeandcodex bd8e3ee008 Align text generation error catches (#3292)
Co-authored-by: codex <[email protected]>
2026-06-20 12:29:24 -07:00
Julius Marmingeandcodex c1d8a22f07 [codex] Structure desktop persisted credential errors (#3239)
Co-authored-by: codex <[email protected]>
2026-06-20 12:28:14 -07:00
Julius Marmingeandcodex 7b791895ad [codex] Structure relay auth persistence errors (#3250)
Co-authored-by: codex <[email protected]>
2026-06-20 12:27:28 -07:00
Julius Marmingeandcodex 4c16c66368 [codex] Structure ACP transport errors (#3251)
Co-authored-by: codex <[email protected]>
2026-06-20 12:25:16 -07:00
Julius Marmingeandcodex 4407a5a6b7 [codex] Structure Codex shadow home errors (#3262)
Co-authored-by: codex <[email protected]>
2026-06-20 12:24:32 -07:00
Julius Marmingeandcodex c7b375e9b0 [codex] Structure Electron window failures (#3276)
Co-authored-by: codex <[email protected]>
2026-06-20 12:23:46 -07:00
Julius Marmingeandcodex abc253d97d [codex] Preserve native SQLite failure context (#3428)
Co-authored-by: codex <[email protected]>
2026-06-20 12:12:41 -07:00
Julius Marmingeandcodex ce11e6facd [codex] Structure desktop browser session errors (#3273)
Co-authored-by: codex <[email protected]>
2026-06-20 12:10:51 -07:00
Julius Marmingeandcodex f1052dd8b1 [codex] Structure Discord release webhook failures (#3285)
Co-authored-by: codex <[email protected]>
2026-06-20 12:09:34 -07:00
Julius Marmingeandcodex e85144a58c [codex] Structure relay delivery attempt errors (#3312)
Co-authored-by: codex <[email protected]>
2026-06-20 12:08:37 -07:00
Julius Marmingeandcodex defd9dfe20 [codex] Structure Electron menu failures (#3317)
Co-authored-by: codex <[email protected]>
2026-06-20 12:07:57 -07:00
Julius Marmingeandcodex 8c03188c1c [codex] Structure preview automation failures (#3333)
Co-authored-by: codex <[email protected]>
2026-06-20 12:07:09 -07:00
Julius Marmingeandcodex 3e5f9f2cdd [codex] Structure browser recording failures (#3330)
Co-authored-by: codex <[email protected]>
2026-06-20 12:06:31 -07:00
Julius Marmingeandcodex 6888276f19 [codex] Sanitize YAML schema diagnostics (#3427)
Co-authored-by: codex <[email protected]>
2026-06-20 12:05:35 -07:00
Julius Marmingeandcodex e06c33c38d [codex] Structure relay Live Activity errors (#3314)
Co-authored-by: codex <[email protected]>
2026-06-20 12:05:13 -07:00
Julius Marmingeandcodex 5f860439e9 [codex] Structure APNs delivery job errors (#3322)
Co-authored-by: codex <[email protected]>
2026-06-20 12:04:27 -07:00
Julius Marmingeandcodex c9159b67b3 [codex] Structure APNs client errors (#3318)
Co-authored-by: codex <[email protected]>
2026-06-20 12:03:43 -07:00
Julius Marmingeandcodex a1b727f62d [codex] Structure relay device persistence errors (#3344)
Co-authored-by: codex <[email protected]>
2026-06-20 12:02:59 -07:00
Julius Marmingeandcodex fdc1e8b3a2 [codex] Structure pairing grant failures (#3386)
Co-authored-by: codex <[email protected]>
2026-06-20 12:02:16 -07:00
Julius Marmingeandcodex c8454ad88a [codex] structure workspace search failures (#3352)
Co-authored-by: codex <[email protected]>
2026-06-20 12:01:31 -07:00
Julius Marmingeandcodex 336d176027 [codex] Structure preview automation errors (#3272)
Co-authored-by: codex <[email protected]>
2026-06-20 12:00:54 -07:00
Julius Marmingeandcodex 204984bf8c [codex] Structure relay deploy output errors (#3340)
Co-authored-by: codex <[email protected]>
2026-06-20 12:00:04 -07:00
Julius Marmingeandcodex be4a38e578 [codex] add structured Electron dialog errors (#3284)
Co-authored-by: codex <[email protected]>
2026-06-20 11:59:27 -07:00
Julius Marmingeandcodex f50a7cddc1 [codex] Structure dev-runner failures (#3283)
Co-authored-by: codex <[email protected]>
2026-06-20 11:58:24 -07:00
Julius Marmingeandcodex 97487d9959 [codex] Structure reference repo sync failures (#3281)
Co-authored-by: codex <[email protected]>
2026-06-20 11:57:48 -07:00
Julius Marmingeandcodex d2e38c5373 [codex] Structure Tailscale command failures (#3257)
Co-authored-by: codex <[email protected]>
2026-06-20 11:56:52 -07:00
Julius Marmingeandcodex 90bd5ee0c1 [codex] structure desktop preview failures (#3244)
Co-authored-by: codex <[email protected]>
2026-06-20 11:55:10 -07:00
Julius Marmingeandcodex 430ece4c0a [codex] Structure Codex app-server request errors (#3258)
Co-authored-by: codex <[email protected]>
2026-06-20 11:54:38 -07:00
Julius Marmingeandcodex 4238a0e769 [codex] Enrich Git VCS driver errors (#3253)
Co-authored-by: codex <[email protected]>
2026-06-20 11:53:53 -07:00
Julius Marmingeandcodex ff0f702c7c [codex] Structure client VCS action errors (#3263)
Co-authored-by: codex <[email protected]>
2026-06-20 11:52:20 -07:00
Julius Marmingeandcodex 1cbe8a7a90 [codex] Structure VCS project config failures (#3315)
Co-authored-by: codex <[email protected]>
2026-06-20 11:51:52 -07:00
Julius Marmingeandcodex 46fdc769d9 [codex] Structure telemetry identity errors (#3306)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:58 -07:00
Julius Marmingeandcodex 0cd0ed1a3d [codex] Sanitize client error log diagnostics (#3405)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:46 -07:00
Julius Marmingeandcodex d53237cbd1 [codex] sanitize ACP native event diagnostics (#3417)
Co-authored-by: codex <[email protected]>
2026-06-20 11:50:14 -07:00
Julius Marmingeandcodex 0e718855b8 [codex] Structure primary environment target failures (#3413)
Co-authored-by: codex <[email protected]>
2026-06-20 11:49:21 -07:00
Julius Marmingeandcodex 731b1a67ac [codex] structure VCS process errors (#3408)
Co-authored-by: codex <[email protected]>
2026-06-20 11:49:08 -07:00
Julius Marmingeandcodex cdfecb36a6 [codex] Structure workspace file system errors (#3274)
Co-authored-by: codex <[email protected]>
2026-06-20 11:48:14 -07:00
Julius Marmingeandcodex f4ef356215 [codex] structure desktop IPC registration errors (#3291)
Co-authored-by: codex <[email protected]>
2026-06-20 11:43:21 -07:00
Julius Marmingeandcodex d60f5c6101 [codex] Structure mobile external link failures (#3363)
Co-authored-by: codex <[email protected]>
2026-06-20 11:42:41 -07:00
Julius Marmingeandcodex eacceb9e7b [codex] Bound shared schema diagnostics (#3424)
Co-authored-by: codex <[email protected]>
2026-06-20 11:41:29 -07:00
Julius Marmingeandcodex 13a4789a5d [codex] Structure terminal adapter startup defects (#3425)
Co-authored-by: codex <[email protected]>
2026-06-20 11:40:36 -07:00
Julius Marmingeandcodex b6e384fb27 [codex] Preserve trace IDs across error causes (#3426)
Co-authored-by: codex <[email protected]>
2026-06-20 11:40:08 -07:00
Julius Marmingeandcodex d8bf307d22 [codex] Enrich process runner errors (#3268)
Co-authored-by: codex <[email protected]>
2026-06-20 11:37:50 -07:00
Julius Marmingeandcodex d512deac84 [codex] Structure preview URL failures (#3275)
Co-authored-by: codex <[email protected]>
2026-06-20 11:37:01 -07:00
Julius Marmingeandcodex 32c7f90d9e [codex] Structure APNs delivery queue errors (#3326)
Co-authored-by: codex <[email protected]>
2026-06-20 11:36:08 -07:00
Julius Marmingeandcodex 2c16edd0cb [codex] Structure desktop bridge state errors (#3381)
Co-authored-by: codex <[email protected]>
2026-06-20 11:32:47 -07:00
Julius Marmingeandcodex 708bc7091d Structure server environment ID failures (#3286)
Co-authored-by: codex <[email protected]>
2026-06-20 11:31:57 -07:00
Julius Marmingeandcodex 7eb7b4f4a3 [codex] Structure release metadata failures (#3296)
Co-authored-by: codex <[email protected]>
2026-06-20 11:31:09 -07:00
Julius Marmingeandcodex e01b1903de [codex] Structure process diagnostics failures (#3389)
Co-authored-by: codex <[email protected]>
2026-06-20 11:30:17 -07:00
Julius Marmingeandcodex 1dc36cef73 Structure relay auth parsing errors (#3290)
Co-authored-by: codex <[email protected]>
2026-06-20 11:29:28 -07:00
Julius Marmingeandcodex 833c8ab7c6 [codex] Remove project setup error constructor wrappers (#3329)
Co-authored-by: codex <[email protected]>
2026-06-20 11:28:33 -07:00
Julius Marmingeandcodex 5b1b35c773 [codex] Preserve desktop shell environment probe failures (#3383)
Co-authored-by: codex <[email protected]>
2026-06-20 11:28:06 -07:00
Julius Marmingeandcodex ee3e2dae78 [codex] Structure remote pairing input errors (#3393)
Co-authored-by: codex <[email protected]>
2026-06-20 11:27:39 -07:00
Julius Marmingeandcodex 9c98cd60e8 Remove persistence error constructor wrappers (#3398)
Co-authored-by: codex <[email protected]>
2026-06-20 11:26:51 -07:00
Julius Marmingeandcodex 48f88d5220 [codex] Structure desktop Clerk bridge failures (#3308)
Co-authored-by: codex <[email protected]>
2026-06-20 11:26:03 -07:00
Julius Marmingeandcodex 2910d9ff01 [codex] Structure preview config failures (#3271)
Co-authored-by: codex <[email protected]>
2026-06-20 11:25:14 -07:00
Julius Marmingeandcodex 2b8e012924 [codex] Structure desktop server exposure errors (#3269)
Co-authored-by: codex <[email protected]>
2026-06-20 11:24:35 -07:00
Julius Marmingeandcodex 49c23221d8 [codex] Structure mobile secure storage failures (#3345)
Co-authored-by: codex <[email protected]>
2026-06-20 11:23:58 -07:00
Julius Marmingeandcodex 5ca7676661 [codex] Structure Claude adapter failures (#3406)
Co-authored-by: codex <[email protected]>
2026-06-20 11:22:57 -07:00
Julius Marmingeandcodex c3e3e26844 [codex] Structure primary environment request failures (#3409)
Co-authored-by: codex <[email protected]>
2026-06-20 11:22:28 -07:00
Julius Marmingeandcodex 1486a4a2b9 [codex] Structure Electron updater errors (#3280)
Co-authored-by: codex <[email protected]>
2026-06-20 11:20:46 -07:00
Julius Marmingeandcodex 1e5f62801b [codex] Structure MCP snapshot failures (#3423)
Co-authored-by: codex <[email protected]>
2026-06-20 11:20:14 -07:00
Julius Marmingeandcodex ed6ba7439d [codex] sanitize provider runtime failure diagnostics (#3414)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:57 -07:00
Julius Marmingeandcodex f98448e872 [codex] Structure relay JWT failures (#3270)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:39 -07:00
Julius Marmingeandcodex bfe61741b8 [codex] Simplify desktop client settings errors (#3265)
Co-authored-by: codex <[email protected]>
2026-06-20 11:19:11 -07:00
Julius Marmingeandcodex 4d3fcacd84 [codex] Type malformed Clerk public config failures (#3422)
Co-authored-by: codex <[email protected]>
2026-06-20 11:18:38 -07:00
Julius Marmingeandcodex 4d790f0064 [codex] Bound relay registration replay diagnostics (#3420)
Co-authored-by: codex <[email protected]>
2026-06-20 11:13:27 -07:00
Julius Marmingeandcodex 3ecf3685ba [codex] structure Bitbucket API failures (#3332)
Co-authored-by: codex <[email protected]>
2026-06-20 11:13:02 -07:00
Julius Marmingeandcodex 716ae73c40 [codex] Structure relay publish signature errors (#3335)
Co-authored-by: codex <[email protected]>
2026-06-20 11:12:31 -07:00
Julius Marmingeandcodex 300d4d566a [codex] Structure missing provider command failures (#3384)
Co-authored-by: codex <[email protected]>
2026-06-20 11:12:02 -07:00
Julius Marmingeandcodex 53a477c2e9 [codex] Structure desktop backend settings read errors (#3379)
Co-authored-by: codex <[email protected]>
2026-06-20 11:11:43 -07:00
Julius Marmingeandcodex d84ebe8319 [codex] Structure process resource sampling failures (#3415)
Co-authored-by: codex <[email protected]>
2026-06-20 11:11:15 -07:00
Julius Marmingeandcodex 5a2c92e86d [codex] Structure Electron app boundary failures (#3301)
Co-authored-by: codex <[email protected]>
2026-06-20 11:10:45 -07:00
Julius Marmingeandcodex 61aade9ea4 [codex] Preserve desktop asset probe failures (#3373)
Co-authored-by: codex <[email protected]>
2026-06-20 11:10:16 -07:00
Julius Marmingeandcodex 04f82ae1f3 [codex] Structure relay environment link errors (#3334)
Co-authored-by: codex <[email protected]>
2026-06-20 11:09:30 -07:00
Julius Marmingeandcodex ce0c20b840 [codex] Structure desktop network interface failures (#3313)
Co-authored-by: codex <[email protected]>
2026-06-20 11:09:02 -07:00
Julius Marmingeandcodex fccecd8749 [codex] Preserve detached desktop action causes (#3371)
Co-authored-by: codex <[email protected]>
2026-06-20 11:08:32 -07:00
Julius Marmingeandcodex 30a084c463 [codex] Preserve mobile composer draft failures (#3348)
Co-authored-by: codex <[email protected]>
2026-06-20 11:08:03 -07:00
Julius Marmingeandcodex 9d5ca2cb7c [codex] Structure Electron protocol teardown failures (#3310)
Co-authored-by: codex <[email protected]>
2026-06-20 11:07:35 -07:00
Julius Marmingeandcodex ac77fe452b [codex] Preserve relay trace error causes (#3377)
Co-authored-by: codex <[email protected]>
2026-06-20 11:07:06 -07:00
Julius Marmingeandcodex 4fbc4f9b20 [codex] Structure mobile project thread validation errors (#3387)
Co-authored-by: codex <[email protected]>
2026-06-20 11:06:38 -07:00
Julius Marmingeandcodex 779c237487 [codex] Structure native view resolution failures (#3353)
Co-authored-by: codex <[email protected]>
2026-06-20 11:06:08 -07:00
Julius Marmingeandcodex 350e229f7a [codex] Structure OAuth scope encoding failures (#3368)
Co-authored-by: codex <[email protected]>
2026-06-20 11:05:40 -07:00
Julius Marmingeandcodex 8112aff7c2 [codex] Structure relay install confirmation conflicts (#3365)
Co-authored-by: codex <[email protected]>
2026-06-20 11:05:24 -07:00
Julius Marmingeandcodex b9e22de6a3 [codex] Preserve desktop update state read failures (#3370)
Co-authored-by: codex <[email protected]>
2026-06-20 11:04:53 -07:00
Julius Marmingeandcodex f3b43a148b [codex] Structure missing client cloud config errors (#3346)
Co-authored-by: codex <[email protected]>
2026-06-20 11:03:09 -07:00
Julius Marmingeandcodex 8331511b97 [codex] structure Electron theme source errors (#3294)
Co-authored-by: codex <[email protected]>
2026-06-20 11:02:37 -07:00
Julius Marmingeandcodex 08650a7424 [codex] Structure web diff worker failures (#3356)
Co-authored-by: codex <[email protected]>
2026-06-20 11:02:07 -07:00
Julius Marmingeandcodex 40d14647db [codex] Structure catalog dependency resolution failures (#3298)
Co-authored-by: codex <[email protected]>
2026-06-20 11:01:36 -07:00
Julius Marmingeandcodex cc69aef4dd [codex] Structure relay domain label errors (#3347)
Co-authored-by: codex <[email protected]>
2026-06-20 11:00:42 -07:00
Julius Marmingeandcodex 71608142c2 [codex] Split preferred editor precondition errors (#3324)
Co-authored-by: codex <[email protected]>
2026-06-20 10:59:54 -07:00
Julius Marmingeandcodex bf1a6501c7 [codex] Preserve review path resolution failures (#3357)
Co-authored-by: codex <[email protected]>
2026-06-20 10:59:10 -07:00
Julius Marmingeandcodex f7867addbe [codex] Structure mobile notification setting failures (#3391)
Co-authored-by: codex <[email protected]>
2026-06-20 10:58:39 -07:00
Julius Marmingeandcodex 7a8bab5d9d [codex] Keep PTY spawn errors structural (#3325)
Co-authored-by: codex <[email protected]>
2026-06-20 10:58:03 -07:00
Julius Marmingeandcodex 06752526b3 [codex] Structure unavailable Bun PTY operations (#3394)
Co-authored-by: codex <[email protected]>
2026-06-20 10:57:33 -07:00
Julius Marmingeandcodex d87ec967bf [codex] Structure empty mobile pairing payload errors (#3372)
Co-authored-by: codex <[email protected]>
2026-06-20 10:56:12 -07:00
Julius Marmingeandcodex e55dd0067d [codex] Structure preview session key errors (#3388)
Co-authored-by: codex <[email protected]>
2026-06-20 10:54:56 -07:00
Julius Marmingeandcodex 8c3755aecc [codex] Structure bootstrap errors (#3256)
Co-authored-by: codex <[email protected]>
2026-06-20 10:54:12 -07:00
Julius Marmingeandcodex b4fe8faa1d [codex] Structure relay activity-row persistence errors (#3305)
Co-authored-by: codex <[email protected]>
2026-06-20 10:42:38 -07:00
Julius Marmingeandcodex 515303edf2 [codex] Preserve desktop user-data probe failures (#3304)
Co-authored-by: codex <[email protected]>
2026-06-20 10:41:55 -07:00
Julius Marmingeandcodex 20734d4a78 [codex] Structure macOS passkey signing failures (#3303)
Co-authored-by: codex <[email protected]>
2026-06-20 10:41:13 -07:00
Julius Marmingeandcodex 86db35ca61 [codex] Structure mobile native static-check failures (#3302)
Co-authored-by: codex <[email protected]>
2026-06-20 10:40:55 -07:00
Julius Marmingeandcodex 97e5cd3bf7 [codex] align server auth Effect services (#3180)
Co-authored-by: codex <[email protected]>
2026-06-20 01:34:52 -07:00
Julius Marmingeandcodex b19fc1b87b [codex] refactor desktop Electron Effect services (#3178)
Co-authored-by: codex <[email protected]>
2026-06-20 01:24:04 -07:00
Julius Marmingeandcodex 2fa37ec183 [codex] Enforce canonical Node namespace imports (#3238)
Co-authored-by: codex <[email protected]>
2026-06-20 01:06:37 -07:00
ss db27502aff [fix/feat:ui] Capitalize Work Log heading (#3228) 2026-06-20 00:52:38 -07:00
ss 6c5fb7930d [fix/feat:ui] Use shared button for model favorites (#3223) 2026-06-20 00:40:57 -07:00
ss 30acfa9c51 [fix/feat:ui] Fix clipped chatbar provider badge (#3224) 2026-06-20 00:39:54 -07:00
Julius Marmingeandcodex f58b6da230 [codex] Preserve workspace RPC error messages (#3222)
Co-authored-by: codex <[email protected]>
2026-06-20 00:39:04 -07:00
Julius Marmingeandcodex 9a1c4875a3 [codex] Remove redundant Effect type annotations (#3229)
Co-authored-by: codex <[email protected]>
2026-06-20 00:37:47 -07:00
Julius Marmingeandcodex 7eda6ba5fc [codex] Migrate desktop shell and SSH Effect services (#3194)
Co-authored-by: codex <[email protected]>
2026-06-20 00:36:41 -07:00
Julius Marmingeandcodex c00e721c04 [codex] Refactor client runtime Effect services (#3200)
Co-authored-by: codex <[email protected]>
2026-06-20 07:17:29 +00:00
Julius Marmingeandcodex b0a3a50448 [codex] Refactor project and workspace Effect services (#3190)
Co-authored-by: codex <[email protected]>
2026-06-20 00:12:46 -07:00
Julius MarmingeandJulius Marminge 79c57170c7 [codex] Make settings environment-scoped by default (#3216)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-20 00:08:32 -07:00
Julius Marmingeandcodex 3900c45f25 Preserve observable Effect error semantics (#3220)
Co-authored-by: codex <[email protected]>
2026-06-19 23:49:51 -07:00
Wout StiensandCodex 8d61172f8b Cosmetic fix: Sync web title with nightly server branding (#3219)
Co-authored-by: Codex <[email protected]>
2026-06-19 23:49:33 -07:00
Julius MarmingeandJulius Marminge dc82f792c3 [codex] Close right panel when its last tab closes (#3221)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 23:48:41 -07:00
Julius MarmingeandJulius Marminge 335e0b59ea Fix PR creation from origin-based worktrees (#3218)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 23:38:54 -07:00
Julius Marmingeandcodex 2fbbe68c24 Clarify Effect error discriminator modeling (#3217)
Co-authored-by: codex <[email protected]>
2026-06-19 23:27:15 -07:00
Julius Marmingeandcodex 65385c0281 [codex] Refactor desktop settings Effect services (#3188)
Co-authored-by: codex <[email protected]>
2026-06-19 22:59:43 -07:00
Julius Marmingeandcodex 6d2dae0627 Preserve full cause chains in Effect error checks (#3215)
Co-authored-by: codex <[email protected]>
2026-06-20 05:53:48 +00:00
Julius Marmingeandcodex 10a8d3fbd9 Tighten structural Effect error checks (#3213)
Co-authored-by: codex <[email protected]>
2026-06-20 05:39:21 +00:00
Julius Marmingeandcodex 0ad1e9d9e4 [codex] Refactor client-runtime Effect services (#3198)
Co-authored-by: codex <[email protected]>
2026-06-19 22:31:45 -07:00
Julius Marmingeandcodex 2f8d3baa88 [codex] finish server process and preview Effect cleanup (#3209)
Co-authored-by: codex <[email protected]>
2026-06-19 22:21:58 -07:00
Julius Marmingeandcodex 6b74476322 Add Effect service conventions check (#3212)
Co-authored-by: codex <[email protected]>
2026-06-19 22:16:45 -07:00
Julius Marmingeandcodex d9e9539862 [codex] Migrate server source control Effect services (#3186)
Co-authored-by: codex <[email protected]>
2026-06-19 22:13:36 -07:00
Julius Marmingeandcodex 7118e43d16 [codex] Refactor checkpointing Effect services (#3181)
Co-authored-by: codex <[email protected]>
2026-06-19 22:05:35 -07:00
Julius Marmingeandcodex 4e8ee13d8f [codex] Align terminal Effect service modules (#3193)
Co-authored-by: codex <[email protected]>
2026-06-19 21:59:32 -07:00
Julius Marmingeandcodex b17b6d50c5 [codex] Complete relay agent activity Effect cleanup (#3210)
Co-authored-by: codex <[email protected]>
2026-06-19 21:37:43 -07:00
Julius Marmingeandcodex ccf8331600 [codex] Align diagnostics and telemetry Effect services (#3189)
Co-authored-by: codex <[email protected]>
2026-06-19 21:29:25 -07:00
Julius Marmingeandcodex ffae12f329 [codex] refactor desktop backend Effect services (#3192)
Co-authored-by: codex <[email protected]>
2026-06-19 21:23:54 -07:00
Julius Marmingeandcodex 01cd564557 [codex] Align desktop preview Effect services (#3199)
Co-authored-by: codex <[email protected]>
2026-06-19 21:22:04 -07:00
Julius Marmingeandcodex 4ee719a094 [codex] refactor server cloud Effect services (#3183)
Co-authored-by: codex <[email protected]>
2026-06-19 21:21:15 -07:00
Julius Marmingeandcodex 01492ebd3b [codex] Refactor agent awareness relay service (#3197)
Co-authored-by: codex <[email protected]>
2026-06-19 21:18:55 -07:00
Julius Marmingeandcodex 93fd972108 [codex] Refactor desktop window and update Effect services (#3202)
Co-authored-by: codex <[email protected]>
2026-06-19 21:17:56 -07:00
Julius Marmingeandcodex df1540f3ac [codex] align persistence Effect service modules (#3184)
Co-authored-by: codex <[email protected]>
2026-06-19 21:14:18 -07:00
Julius Marmingeandcodex d5a72d5be1 [codex] align relay agent activity Effect services (#3179)
Co-authored-by: codex <[email protected]>
2026-06-19 21:13:01 -07:00
Julius Marmingeandcodex 742dd7af0d [codex] Standardize Effect protocol adapter services (#3201)
Co-authored-by: codex <[email protected]>
2026-06-19 21:11:33 -07:00
Julius Marmingeandcodex 5c1ac92257 [codex] normalize server process and preview Effect services (#3191)
Co-authored-by: codex <[email protected]>
2026-06-19 21:09:22 -07:00
Julius Marmingeandcodex 8bfdacf206 [codex] Use namespace imports for desktop core services (#3207)
Co-authored-by: codex <[email protected]>
2026-06-19 21:04:49 -07:00
Julius Marmingeandcodex b6302784f8 [codex] Refactor review and text generation services (#3196)
Co-authored-by: codex <[email protected]>
2026-06-19 21:04:13 -07:00
Yash Singh 9544e72d08 chore: run eas only when labelled (#3208) 2026-06-20 03:28:51 +00:00
Julius Marmingeandcodex 938b19a6bb [codex] Normalize Desktop IPC Effect service (#3203)
Co-authored-by: codex <[email protected]>
2026-06-20 03:10:33 +00:00
Julius Marmingeandcodex 3b56dc17a5 [codex] Refactor primary HTTP Effect service (#3205)
Co-authored-by: codex <[email protected]>
2026-06-19 20:07:29 -07:00
Julius Marminge d2c0a6a48f Add diff scope switching and provider update settings (#3169) 2026-06-19 20:02:20 -07:00
Julius Marmingeandcodex 1cf3647da6 [codex] Normalize server core Effect service modules (#3187)
Co-authored-by: codex <[email protected]>
2026-06-19 19:58:48 -07:00
Julius Marmingeandcodex 53d0107759 [codex] align relay foundation Effect services (#3182)
Co-authored-by: codex <[email protected]>
2026-06-19 19:56:36 -07:00
Julius Marmingeandcodex 60b16d1f28 [codex] Refactor desktop app Effect services (#3185)
Co-authored-by: codex <[email protected]>
2026-06-19 19:42:41 -07:00
Julius Marmingeandcodex ab0baaa886 [codex] Inline contracts request-context service shapes (#3204)
Co-authored-by: codex <[email protected]>
2026-06-20 02:34:44 +00:00
Julius Marminge 753bc4672d Harden preview ownership and option-based secret handling (#3172) 2026-06-19 17:38:45 -07:00
Julius Marmingeandcodex e29ad7604b Unify mobile typography tokens across the app (#3162)
Co-authored-by: codex <[email protected]>
2026-06-19 16:49:35 -07:00
Julius Marminge cdaba7fa8b Share thread state idle TTL across client atoms (#3163) 2026-06-19 13:15:19 -07:00
Julius MarmingeandJulius Marminge fbf6263876 Only show enabled providers in picker sidebar (#3168)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 19:14:06 +00:00
c08b968f4e Use Effect schema decoders for JSON parsing (#3060)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-19 11:48:24 -07:00
Icarus Wingsandcodex d9f59be704 feat(sidebar): worktree indicator on session rows (#3057)
Co-authored-by: codex <[email protected]>
2026-06-19 11:23:47 -07:00
a4446e263d Improve idiomatic Effect usage in config and Tailscale paths (#3073)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-19 11:21:39 -07:00
Icarus Wingsandcodex 494350cc0b feat(composer): clickable PR pill next to branch selector (#3065)
Co-authored-by: codex <[email protected]>
2026-06-19 11:20:59 -07:00
Wout Stiensandcodex 7dc182337c [codex] fix: show nightly badge from primary web server version (#3103)
Co-authored-by: codex <[email protected]>
2026-06-19 11:16:37 -07:00
13917df1fe Use idiomatic Effect options for server secret reads (#3110)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-19 11:15:35 -07:00
Ulises Britosandcodex 5d4e2fae01 feat: allow disabling provider update checks (#3130)
Co-authored-by: codex <[email protected]>
2026-06-19 11:07:23 -07:00
Julius Marmingeandcodex 3e01c4bc57 Migrate desktop auth to Clerk bridge (#3092)
Co-authored-by: codex <[email protected]>
2026-06-19 10:28:28 -07:00
Mika CohenandJulius Marminge 20f37f367a Avoid repeated theme DOM sync during startup (#2779)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-19 05:46:12 +00:00
Soorria SaruvaandCursor 804d44cfb1 fix(ssh): fix support for remotes that use fnm (#2641)
Co-authored-by: Cursor <[email protected]>
2026-06-18 22:45:04 -07:00
Ishan 0651af92b8 fix(server): use bound host for MCP endpoint (#3114) 2026-06-18 20:41:14 -07:00
Julius Marminge 52a24c8902 Add origin-based worktree bootstrap option (#3157) 2026-06-18 20:39:52 -07:00
30034ecedc Add archived threads and mobile file viewer (#3155)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-18 20:24:48 -07:00
Mike Olson 1fcc57af13 fix(web): Remove saved environments atomically (#2917) 2026-06-18 20:20:53 -07:00
Julius Marmingeandcodex e95b57dc26 [codex] Rewrite client connection architecture (#2978)
Co-authored-by: codex <[email protected]>
2026-06-18 13:10:32 -07:00
Theo BrowneandClaude Opus 4.8 3bdaa6e100 Polish marketing homepage: nav, hero, and endorsements (#3137)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-06-17 23:23:14 -07:00
Wout StiensandJulius Marminge b7b00bfb9d fix: Adapt destructive menu icon to dark mode (#3126)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-18 05:43:47 +00:00
Ryan Skinner ae2b523503 fix(mobile): bump react-native-shiki-engine to 0.3.12 (#3120) 2026-06-17 22:33:01 -07:00
Andrew Forster 75b3b3c48a [codex] Make background VCS fetch non-interactive (#3133) 2026-06-17 22:49:09 +00:00
Julius Marminge b489ea52a8 Improve inline panel, file preview, and MCP session handling (#3121) 2026-06-16 22:40:22 -07:00
Julius Marmingeandcodex 3a5ec9464b Render the plan surface in the inline right panel (#3118)
Co-authored-by: codex <[email protected]>
2026-06-16 17:30:22 -07:00
Julius Marminge e56bb200fa Add right-panel bulk close and tab context menu actions (#3116) 2026-06-16 16:39:40 -07:00
Julius Marminge c2ca9de33a Add file preview comments and task toggles (#3115) 2026-06-16 16:22:18 -07:00
Icarus WingsandClaude Opus 4.8 60b546cf01 Double-click a sidebar thread row to rename (#3064)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-16 11:04:47 -07:00
Jan JaapandClaude Haiku 4.5 4b73827334 fix(settings): disable auto-open of task sidebar by default (#2421)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
2026-06-16 10:58:27 -07:00
Julius Marminge a5efb7cb6b Parallelize VCS status refresh and status reads (#3112) 2026-06-16 10:54:00 -07:00
Julius Marminge 8f9911f79d Add DELETE-based MCP session termination (#3113) 2026-06-16 10:53:25 -07:00
Julius Marmingeandcodex 689a882045 [codex] Add native mobile composer and markdown (#3101)
Co-authored-by: codex <[email protected]>
2026-06-16 09:31:57 -07:00
Julius Marminge 85fe62d402 Stage fff native binaries in desktop builds (#3109) 2026-06-16 09:12:32 -07:00
Julius Marmingeandcodex 708d5383a9 [codex] Trace first-party relay clients (#2995)
Co-authored-by: codex <[email protected]>
2026-06-16 00:11:29 -07:00
Wout Stiens 5cd2744100 [codex] Fix terminal line height for QR readability (#3096) 2026-06-16 07:08:17 +00:00
Julius Marminge d12da198ad Use fff for workspace search queries (#3099) 2026-06-16 00:02:03 -07:00
d0a7d18cdb [codex] Fix first browser annotation capture (#3095)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-16 00:10:28 +00:00
Julius Marminge 71ea5fa1ab Show disabled reasons for unavailable right panel surfaces (#3093) 2026-06-15 23:21:06 +00:00
Julius Marminge 9d5e632d4d Tighten workspace control spacing in the header
- Align header controls with the 12px right inset
- Use a smaller control offset in window controls overlay mode
2026-06-15 16:05:36 -07:00
Julius Marminge c2d44a312c Unify compact subheaders and diff file navigation
- Add shared compact subheader styling for preview, file, and diff panels
- Open diff files in the thread file viewer when available
- Fix macOS cursor auto-hide and Option-modified shortcut matching
2026-06-15 15:58:03 -07:00
Julius Marminge de8bdc10fa Add workspace file browser and preview panel (#3087) 2026-06-15 14:17:07 -07:00
477795697d refactor: resolve host process state through Effect (#2959)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-14 16:47:56 -07:00
Icarus Wings a23b83314e fix(desktop): mac start:desktop crash from rewritten framework symlinks (#3058) 2026-06-14 18:52:22 +00:00
Julius Marminge ce90563709 Preserve diff surface when toggling right panel (#3083) 2026-06-14 11:41:36 -07:00
Julius Marminge 31e68229d6 Wrap authorized clients in fading scroll area (#3085) 2026-06-14 11:41:26 -07:00
Julius Marminge 1db585878e Guard VCS status updates against stale targets (#3084) 2026-06-14 11:41:12 -07:00
JustMarkDev 56e57de947 Fix Bitbucket source control availability toggle 2026-06-14 11:07:19 -07:00
Julius Marminge 3a0623f1cd rm test artifacts 2026-06-13 22:18:37 -07:00
Julius Marminge cd91ec75f3 Remove outdated plans for shared HTTP MCP server and visible preview browser automation via CDP. Consolidate and refine the architecture and process models for the new preview automation framework, including updated contracts, server-side broker, and desktop integration. Introduce new WS methods for client communication and enhance security measures for token management. Ensure comprehensive testing strategies are in place for all components. 2026-06-13 22:18:37 -07:00
Julius Marminge d4ba9e9618 Document browser preview phase 0.5 findings and plans
- Add phase 0 and 0.5 ADRs, findings, and spike notes
- Update browser preview docs and supporting UI/test files
- Record the chosen renderer, automation, recording, tunnel, and input decisions
2026-06-13 22:18:37 -07:00
Julius Marminge c1792bc9a6 Use real preview tooltips 2026-06-13 22:18:37 -07:00
Julius Marminge 1b4317ec35 Restore terminal drawer header toggle 2026-06-13 22:18:37 -07:00
Julius Marminge f452d63fef Fix terminal browser test mock 2026-06-13 22:18:37 -07:00
Julius Marminge 18a49abcec Fix preview CI test fixtures 2026-06-13 22:18:37 -07:00
Julius Marminge 85d5df6256 Unify browser asset preview routing
- Replace attachment and favicon routes with signed asset URLs
- Harden workspace and attachment asset resolution
- Update browser preview components and shared contracts
2026-06-13 22:18:37 -07:00
Julius Marminge b5b769dddf Prevent stale preview snapshots from resurrecting sessions
- Track preview store revisions per thread
- Ignore stale SWR results while revalidating
- Avoid restoring closed sessions from outdated data
2026-06-13 22:18:37 -07:00
Julius Marminge 3c7862edd7 Add SWR preview session state and resubscribe handling
- Fetch preview sessions through atom-backed SWR state
- Recover browser preview sessions after reconnects
- Ignore older streamed snapshots when SWR revalidates
2026-06-13 22:18:37 -07:00
Julius Marminge d8fe3d72c8 Scope preview listeners and control sessions
- Tie preview and debugger listeners to Effect scopes
- Factor shared automation helpers for snapshot and input handling
- Improve cleanup for browser preview sessions and port scanning
2026-06-13 22:18:37 -07:00
Julius Marminge 70ec39ae80 Port preview manager to Effect-based browser sessions
- derive preview partitions through `BrowserSession`
- serialize session state and async preview control flow
- update tests for screenshot, automation, and partition behavior
2026-06-13 22:18:37 -07:00
Julius Marminge 3d9e8dea7d Refactor desktop preview IPC onto shared manager
- Move preview session and IPC wiring into the new preview module
- Tighten IPC validation with schema-based handlers
- Update preview asset paths and tests for the browser preview port
2026-06-13 22:18:37 -07:00
Julius Marminge f7c422d581 Refactor MCP services into top-level modules
- Move MCP session registry and preview broker out of `Layers/` and `Services/`
- Update imports, tests, and server wiring to use the new module layout
2026-06-13 22:18:37 -07:00
Julius Marminge dd739c880d Port browser preview annotations to desktop
- Add IPC and runtime plumbing for preview annotation theming
- Generate and ship annotation CSS for the desktop overlay
- Add pointer and artifact handling for browser preview interactions
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 6c6740e381 Refine collaborative browser preview
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marminge 29150b5736 Add shared MCP preview automation 2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 07c6d70b91 Add preview annotation capture tooling
- Add structured annotation payload validation and tests
- Update preview preload to capture selected elements, regions, and strokes
- Wire new preview annotation UI into the web app

Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 50bc18b208 fix(preview): declare RPC authorization scopes
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 63d42a5e58 fix(preview): initialize and open browser reliably
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 9b43123ba2 fix(preview): port browser preview to current main
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Aiden Bai 17fb0e4a9a feat(preview): element-pick attachments + sandboxed picker preload
Adds an in-page element picker to the preview browser. Clicking the
crosshair button in the chrome row activates a blue-highlight picker
inside the guest webview; clicking an element captures its component
name (via react-grab), source location, html/css preview, and selector,
then attaches it to the chat composer as a chip that serializes into an
`<element_context>` block in the outgoing message.

Architecture:
- Per-`<webview>` preload bundle (`preview-pick-preload.cjs`) renders
  the overlay, hosts the picker event loop, and bubbles the picked
  payload back to main via the per-WebContents `wc.ipc` channel (not
  `sendToHost`, which only fires on the host renderer's <webview>
  element and never reaches main).
- Main coordinates via `PreviewViewManager.pickElement(tabId)`, which
  cancels any in-flight session, force-focuses the guest (so the first
  click on a remote page actually reaches the preload), then awaits the
  payload. User-initiated cancels (Escape, beforeunload) echo `null`
  back to main; main-initiated cancels and supersession tear down
  silently to avoid the new-pick-resolves-with-stale-null race.
- Renderer fetches partition + webPreferences + preload URL in a single
  `getPreviewConfig()` IPC call, snapshots the previously-focused host
  element before triggering a pick, and restores focus when the pick
  resolves so the user's textarea cursor isn't lost.

Security posture for the guest webview:
- `webpreferences="contextIsolation=false,sandbox=true,nodeIntegration=false"`
  centralized in `preview-webview-preferences.ts`. contextIsolation off
  is required so react-grab's `getElementContext` can reach the page's
  React DevTools hook on `globalThis`. sandbox stays on so the page
  cannot reach Node APIs even with shared globals (without it, the
  preload's `require` would land on the page's `globalThis` and any
  third-party site could send arbitrary IPC to main).
- Defense in depth: a `will-attach-webview` handler in main, gated on
  the preview partition, force-pins `sandbox: true`, all
  `nodeIntegration*: false`, and the absolute preload PATH (not URL —
  that field rejects file:// URLs with "preload script must have
  absolute path" and silently disables the picker).

Composer + transcript integration:
- New `elementContexts` slice in `composerDraftStore` (mirrors the
  terminal-context slice: dedup by selector+tag+component+url, persist
  via partializer, restore on send-failure retry).
- `ComposerPendingElementContexts` chip row above the editor.
- `deriveDisplayedUserMessageState` now strips both `<element_context>`
  AND `<terminal_context>` blocks (element first, since it's appended
  last) and exposes element entries to `MessagesTimeline`, which renders
  them as compact chips beneath the message body.
- Pick button is disabled with explanatory tooltip when the page failed
  to load (the React `<PreviewUnreachable>` overlay covers the webview,
  so picks would silently dangle otherwise).

Tests added:
- `preview-webview-preferences.test.ts` locks down the security flags
  (contextIsolation=false, sandbox=true, nodeIntegration=false, no
  whitespace, only true/false literal values).
- `preview-pick-label-position.test.ts` covers the floating-label
  clamp/flip math (no off-screen overflow, flip-below when no room
  above, etc.).
- `picked-element-payload.test.ts` validator coverage.
- `elementContext.test.ts` for the serialization round-trip,
  normalization, dedup, and label formatting.
- `composerDraftStore.test.ts` element-contexts slice (add, dedup,
  remove, set, clear, persistence round-trip).
- `ChatView.logic.test.ts` sendable-content-with-element-only.

Build: new `tsdown` entry inlines react-grab + bippy into the picker
preload bundle (~59KB / 19KB gzipped).
2026-06-13 22:18:37 -07:00
Aiden Bai 43e8bbd7ae fix 2026-06-13 22:18:37 -07:00
Aiden Bai 52c77c1ec4 feat(preview): in-app browser preview panel
Adds a desktop-only browser preview that lives in the right panel slot
alongside plan/diff. Lets the user point an Electron <webview> at any
URL — typed into a chrome-style URL bar, clicked from the empty-state
list of detected localhost dev servers, or auto-opened by a project
script with `previewUrl` set. Single-tab per thread.

Server (Effect/Layers):
- PreviewManager: per-(thread, tab) session metadata via SynchronizedRef
  + PubSub<PreviewEvent>; survives WS reconnect via `list`/replay.
- PreviewPortScanner: lsof on macOS/Linux, TCP probe fallback on
  Windows; reference-counted polling so we only scan when subscribed.
- WS RPC + streams (`preview.open|navigate|refresh|close|list|reportStatus`,
  `subscribePreviewEvents`, `subscribeDiscoveredLocalServers`).

Desktop:
- PreviewViewManager owns Chromium WebContents per tab, mediates
  navigation/zoom/devtools/clear-storage. registerWebview gates by
  webContents.getType() === "webview" and host-window match.
- IPC channels for create/close/register/navigate/back/forward/refresh/
  zoom/hardReload/openDevTools/clearCookies/clearCache/getBrowserPartition.
- Forwards app-level shortcuts (mod+shift+J, mod+K, mod+,, mod+W) from
  the webview back to the main window.
- Persisted browser session partition (cookies, cache).

Web:
- PreviewPanel/PreviewView/PreviewWebview render the surface; chrome row
  with back/forward/refresh + URL input + Open-in-browser + 3-dot menu
  (Hard reload, DevTools, Zoom −/+/reset, Clear cookies/cache).
- usePreviewSession subscribes to server events; usePreviewBridge
  mirrors desktop state into the store and forwards Loading→Success/
  LoadFailed back to the server.
- previewStateStore: per-thread snapshot + desktopOverlay + recently-
  seen URLs (Zustand).
- rightPanelStore arbitrates plan vs. preview vs. diff; ChatView's
  toggles strip the `?diff=1` URL hint when switching to preview and
  vice versa so the panels are mutually exclusive.
- Top-nav Globe toggle in ChatHeader (desktop builds only) and a
  `mod+shift+J` keybinding routed via a typed previewActionBus.
- PreviewEmptyState lists detected localhost servers (scanner +
  configured project URLs + recently-seen) with live "listening" pulse.
- PreviewUnreachable: theme-aware port of Chromium's "site can't be
  reached" page.
- Resizable inline panel (RightPanelResizeHandle + useResizableWidth);
  width persists to localStorage on drag-end.
- Terminal link "Open in preview" context-menu integration for loopback
  URLs.

Contracts:
- preview.ts schemas (PreviewSessionSnapshot, PreviewNavStatus,
  PreviewEvent, RPC inputs/results, DiscoveredLocalServer).
- ProjectScript schema gains optional `previewUrl` + `autoOpenPreview`.
- New keybinding commands: preview.toggle/refresh/focusUrl/zoomIn/Out/
  resetZoom; new `when:` contexts `previewFocus` / `previewOpen`.

Shared:
- @t3tools/shared/preview: normalizePreviewUrl, isPreviewableUrl,
  isLoopbackHost, newPreviewTabId, LSOF_LOCAL_HOST_TOKENS.

Tests:
- contracts: schema decode tests for all preview events/snapshots/inputs.
- shared: URL normalization coverage.
- server: PreviewManager (open/navigate/reportStatus/refresh/close,
  multi-subscriber isolation, idempotency); PortScanner (lsof parsing
  including IPv6, TCP probe, reference-counted polling).
- web: previewStateStore (per-tab event application, dedupe,
  reconnect recovery); rightPanelStore arbitration.
2026-06-13 22:18:37 -07:00
Aiden Bai d6eb386e3d planning 2026-06-13 22:18:37 -07:00
HuakunandJulius Marminge d25090cf6d fix: avoid sending composer during IME enter (#2817)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:14:13 +00:00
Mika CohenandJulius Marminge ae39bacf0e Handle non-resumable pending user input (#2766)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:13:34 +00:00
Julius MarmingeandJulius Marminge 1ea17026ee [codex] fix slow websocket shutdown (#2869)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 01:39:25 +00:00
Julius Marmingeandcodex 649f4328ea [codex] Refine inline tool call timeline UI (#3052)
Co-authored-by: codex <[email protected]>
2026-06-11 18:18:27 -07:00
Magnus Alexander StrømsengandJulius Marminge 7db034905b fix(git): disable external diff for patch output (#2553)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-11 18:18:13 -07:00
Julius MarmingeandClaude Fable 5 57f6bf7edb Fix turn fold proejctions (#3041)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 23:51:43 -07:00
Julius Marmingeandcodex 0baf1986e8 [codex] Reduce Git status polling churn (#3037)
Co-authored-by: codex <[email protected]>
2026-06-10 17:10:19 -07:00
Julius Marmingeandcodex ae7e88b0e0 [codex] Sync app-server protocol, service tiers, and provider startup (#3036)
Co-authored-by: codex <[email protected]>
2026-06-10 16:24:19 -07:00
1916ac6d55 Rework message metadata, timestamps, and tool work log rows (#3022)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 14:38:42 -07:00
Julius Marmingeandcodex 343061a053 Misc chrome polish: header badges, plan sidebar, diff panel, empty state (#3027)
Co-authored-by: codex <[email protected]>
2026-06-10 12:25:03 -07:00
0b40ea62e1 Extract changed files card with compact aligned diff stats (#3023)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:27:32 +00:00
a4757c2656 Composer polish: focus ring, send/stop buttons, command menu, context meter, answer panel (#3018)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:02:32 +00:00
3efabdcd3a Polish web context menu fallback and sidebar icon actions (#3025)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 07:29:21 +00:00
c5f7cd40ba Polish branch picker trigger, scroll fade, and list layout (#3024)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-06-10 07:13:34 +00:00
e2db800f7c Provider env vars table and reworked accent color picker (#3026)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 23:27:59 -07:00
31533466b0 Model picker UI Improvements, Virtualize Model List (#3021)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 06:22:55 +00:00
7f741a56d1 Misc markdown styling improvements (#3017)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-06-09 21:21:58 -07:00
RuzbyteandJulius Marminge cc9e81ac93 fix(marketing) : marketing showing wrong icons on linux (#2696)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 20:04:36 -07:00
238715fd6f Polish dialog/alert surfaces and unauthenticated provider banner (#3016)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:52:16 -07:00
b03bc4b52d Mute icons in labeled controls and suppress popup focus rings (#3015)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:15:09 -07:00
aca14507f7 Bundle DM Sans and JetBrains Mono fonts instead of Google Fonts (#3014)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 16:57:38 -07:00
t3-code[bot] 04f7f32ace chore(release): prepare v0.0.27 2026-06-09 21:14:36 +00:00
Julius Marmingeandcodex a3422a9bb5 Fix Clerk browser test mock (#3013)
Co-authored-by: codex <[email protected]>
2026-06-09 20:38:20 +00:00
Julius Marmingeandcodex 22f9f3058b [codex] Rebrand T3 Cloud as T3 Connect (#3011)
Co-authored-by: codex <[email protected]>
2026-06-09 12:25:02 -07:00
t3-code[bot] 983a8c7fa6 chore(release): prepare v0.0.26 2026-06-09 17:53:22 +00:00
Julius Marmingeandcodex de58ec8e24 Add Claude Fable 5 model (#3009)
Co-authored-by: codex <[email protected]>
2026-06-09 17:39:18 +00:00
Julius Marmingeandcodex 8e6f4229da [codex] Fix main CI Effect test runtimes (#3008)
Co-authored-by: codex <[email protected]>
2026-06-09 09:43:03 -07:00
Milosz JankiewiczandJulius Marminge 38ea6d483e feat(grok): add Grok CLI provider via ACP (#2809)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 09:28:40 -07:00
Julius Marmingeandcodex 0e4a43519f [codex] Extract infrastructure, telemetry, and test tooling (#2994)
Co-authored-by: codex <[email protected]>
2026-06-07 20:21:47 -07:00
Julius Marmingeandcodex 3ea6adf17d [codex] Enrich relay authorization diagnostics (#2977)
Co-authored-by: codex <[email protected]>
2026-06-05 18:01:34 -07:00
Julius Marminge a56496c7f2 Annotate relay error spans with schema fields (#2976) 2026-06-05 16:35:14 -07:00
b76f161d55 fix(desktop): stop looping macOS TCC permission prompts (#2745)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 12:07:18 -07:00
Peter Hozák 75257d64e9 "claude system message" instead of "runtime warning" when using 4.8 from claude code (#2972) 2026-06-05 11:27:37 -07:00
Abdul AzeezandJulius Marminge e1ce9f8500 fix: handle Claude Agent SDK 0.3.x system messages to stop runtime-warning flood (#2872)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 18:26:32 +00:00
Julius Marminge 602148f8fe fix(cloud): use Electron fetch for proxying Clerk IPC requests (#2973) 2026-06-05 11:08:34 -07:00
2190 changed files with 259283 additions and 100089 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).
+18 -2
View File
@@ -1,5 +1,5 @@
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
@@ -8,5 +8,21 @@
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
# returns a different RP ID or when multiple domains must be entitled.
# T3CODE_APPLE_TEAM_ID=ABC1234567
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# 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
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
+1 -46
View File
@@ -38,6 +38,7 @@ jobs:
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
test:
name: Test
@@ -60,52 +61,6 @@ jobs:
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
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: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
+1 -1
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Cloud relay
name: Deploy T3 Connect relay
on:
push:
+6 -1
View File
@@ -2,10 +2,12 @@ name: Mobile EAS Preview
on:
pull_request:
types: [opened, reopened, synchronize, labeled, unlabeled]
jobs:
preview:
name: EAS Preview
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
@@ -55,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
+164 -3
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Cloud public config
name: Resolve T3 Connect public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
@@ -180,12 +180,46 @@ jobs:
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3code-relay...
- id: relay_state
name: Read production relay tracing config
shell: bash
run: |
vp run --filter t3code-relay deploy \
--stage prod \
--read-state \
--github-output \
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
- name: Upload relay client tracing config
uses: actions/upload-artifact@v7
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing.env
if-no-files-found: error
retention-days: 1
- id: public_config
name: Resolve production relay public config
shell: bash
@@ -218,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:
@@ -272,9 +360,30 @@ jobs:
cache: true
run-install: true
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- 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
@@ -377,6 +486,9 @@ jobs:
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
@@ -404,15 +516,31 @@ jobs:
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
exit 1
fi
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
security cms -D -i "$profile_path" >/dev/null
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
echo "macOS signing enabled."
args+=(--signed)
else
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
# 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" \
@@ -508,6 +636,20 @@ jobs:
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -646,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 }}
@@ -670,6 +813,20 @@ jobs:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -715,7 +872,11 @@ 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:-}" \
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
+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
@@ -0,0 +1,92 @@
---
title: Effect Service Conventions
model: claude-opus-4-8
effort: high
input: full_diff
tools:
- browse_code
- git_tools
- github_api_read_only
- modify_pr
include:
- "apps/**/*.ts"
- "apps/**/*.tsx"
- "packages/**/*.ts"
- "packages/**/*.tsx"
- "infra/**/*.ts"
- "infra/**/*.tsx"
conclusion: failure
showToolCalls: true
---
# Effect service review
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
## Imports and module namespaces
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
## Service definition
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
- 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.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- 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
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
## Change discipline
- Preserve useful comments, invariants, and specification documentation while moving code.
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
## 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.
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": {}
}
+9 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.28",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -12,6 +12,8 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
@@ -20,13 +22,17 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
},
"devDependencies": {
"@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:"
},
"productName": "T3 Code (Alpha)"
@@ -0,0 +1,40 @@
import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { compile } from "tailwindcss";
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
NodeFSP.readFile(sourcePath, "utf8"),
NodeFSP.readFile(preloadPath, "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
);
const compilerInput = [
themeSource,
preflightSource,
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
].join("\n");
const compiler = await compile(compilerInput, { base: appRoot });
const css = compiler.build([...candidates]);
const encodedCss = `'${css
.replaceAll("\\", "\\\\")
.replaceAll("'", "\\'")
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await NodeFSP.writeFile(outputPath, moduleSource);
+25 -13
View File
@@ -1,8 +1,13 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
import {
desktopDir,
resolveDevProtocolClient,
resolveElectronLaunchCommand,
} from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
@@ -29,6 +34,8 @@ const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
const hostPlatform = NodeOS.platform();
await waitForResources({
baseDir: desktopDir,
@@ -53,19 +60,21 @@ const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (process.platform === "win32" || typeof pid !== "number") {
if (hostPlatform === "win32" || typeof pid !== "number") {
return;
}
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
if (process.platform === "win32") {
if (hostPlatform === "win32") {
return;
}
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
stdio: "ignore",
});
}
function startApp() {
@@ -79,7 +88,8 @@ function startApp() {
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const app = spawn(resolveElectronPath(), launchArgs, {
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -172,8 +182,8 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(
join(desktopDir, directory),
const watcher = NodeFS.watch(
NodePath.join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
@@ -189,12 +199,14 @@ function startWatchers() {
}
function killChildTree(signal) {
if (process.platform === "win32") {
if (hostPlatform === "win32") {
return;
}
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
stdio: "ignore",
});
}
async function shutdown(exitCode) {
+208 -118
View File
@@ -1,28 +1,18 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import { spawnSync } from "node:child_process";
import {
copyFileSync,
chmodSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
const repoRoot = resolve(desktopDir, "..", "..");
const devBundleIdSuffix = basename(repoRoot)
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
export const desktopDir = NodePath.resolve(__dirname, "..");
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
const devBundleIdSuffix = NodePath.basename(repoRoot)
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "");
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -30,29 +20,36 @@ 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 = 10;
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
function resolveDevelopmentProtocolCallbackPort() {
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
return configuredPort + 1;
}
return 13774;
}
const LAUNCHER_VERSION = 14;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
"dev",
"blueprint-macos-1024.png",
);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
encoding: "utf8",
});
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
encoding: "utf8",
});
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
@@ -63,16 +60,24 @@ function setPlistString(plistPath, key, value) {
function setPlistJson(plistPath, key, value) {
const serialized = JSON.stringify(value);
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
const replaceResult = NodeChildProcess.spawnSync(
"plutil",
["-replace", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
encoding: "utf8",
});
const insertResult = NodeChildProcess.spawnSync(
"plutil",
["-insert", key, "-json", serialized, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
@@ -82,7 +87,7 @@ function setPlistJson(plistPath, key, value) {
}
function runChecked(command, args) {
const result = spawnSync(command, args, { encoding: "utf8" });
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
if (result.status === 0) {
return;
}
@@ -95,39 +100,43 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
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],
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
writeFileSync(
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)}`),
'for arg in "$@"; do',
' case "$arg" in',
" t3code-dev://auth/callback*)",
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
" fi",
" ;;",
" esac",
"done",
`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,
}),
);
chmodSync(targetBinaryPath, 0o755);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
function registerMacLauncherBundle(appBundlePath) {
@@ -157,21 +166,24 @@ function registerMacLauncherBundle(appBundlePath) {
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
mkdirSync(runtimeDir, { recursive: true });
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
if (!existsSync(developmentMacIconPngPath)) {
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
}
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
if (
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
) {
return generatedIconPath;
}
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
const iconsetDir = join(iconsetRoot, "icon.iconset");
mkdirSync(iconsetDir, { recursive: true });
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
NodeFS.mkdirSync(iconsetDir, { recursive: true });
try {
for (const size of [16, 32, 128, 256, 512]) {
@@ -181,7 +193,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(size),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}.png`),
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
]);
const retinaSize = size * 2;
@@ -191,7 +203,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
String(retinaSize),
developmentMacIconPngPath,
"--out",
join(iconsetDir, `icon_${size}x${size}@2x.png`),
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
}
@@ -204,15 +216,16 @@ function ensureDevelopmentIconIcns(runtimeDir) {
);
return defaultIconPath;
} finally {
rmSync(iconsetRoot, { recursive: true, force: true });
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
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", [
{
@@ -221,9 +234,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
},
]);
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
@@ -235,7 +248,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
];
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
const infoPlistPath = join(
const infoPlistPath = NodePath.join(
appBundlePath,
"Contents",
"Frameworks",
@@ -243,7 +256,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
"Contents",
"Info.plist",
);
if (!existsSync(infoPlistPath)) {
if (!NodeFS.existsSync(infoPlistPath)) {
continue;
}
@@ -259,77 +272,154 @@ function patchHelperBundleInfoPlists(appBundlePath) {
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = join(runtimeDir, "metadata.json");
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"),
};
}
mkdirSync(runtimeDir, { recursive: true });
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 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");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
appBundleId: APP_BUNDLE_ID,
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
};
const currentMetadata = readJson(metadataPath);
if (
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;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
// verbatimSymlinks keeps the framework's relative symlinks intact
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
// rewrites them to absolute paths into node_modules, which escape the
// bundle and crash sandboxed helper processes (icudtl.dat not found).
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
recursive: true,
verbatimSymlinks: true,
});
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);
}
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (hostPlatform !== "linux") {
return true;
}
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = NodeFS.statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch {
return false;
}
}
function resolveLinuxSandboxArgs(electronBinaryPath) {
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
return [];
}
console.warn(
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
);
return ["--no-sandbox"];
}
export function resolveElectronPath() {
ensureElectronRuntime();
const electronBinaryPath = resolveElectronBinaryPath();
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (process.platform !== "darwin") {
if (hostPlatform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
export function resolveElectronLaunchCommand(args = []) {
const electronPath = resolveElectronPath();
return {
electronPath,
args: [...resolveLinuxSandboxArgs(electronPath), ...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 (process.platform !== "darwin" || !isDevelopment) {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const electronBinaryPath = resolveElectronBinaryPath();
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
appBundleId: APP_BUNDLE_ID,
};
}
@@ -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");
});
});
@@ -1,13 +1,17 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
const require = createRequire(import.meta.url);
const require = NodeModule.createRequire(import.meta.url);
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostPlatform = NodeOS.platform();
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
const hostArch = NodeOS.arch();
function getPlatformPath() {
switch (process.platform) {
switch (hostPlatform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
@@ -17,32 +21,34 @@ function getPlatformPath() {
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
}
}
function ensureExecutable(filePath) {
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
if (hostPlatform !== "win32") {
NodeFS.chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
const pathFile = NodePath.join(electronDir, "path.txt");
const currentPath = NodeFS.existsSync(pathFile)
? NodeFS.readFileSync(pathFile, "utf8")
: undefined;
if (currentPath !== platformPath) {
writeFileSync(pathFile, platformPath);
NodeFS.writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
const paths = [NodePath.join(electronDir, "dist", platformPath)];
if (process.platform === "darwin") {
if (hostPlatform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
NodePath.join(
electronDir,
"dist",
"Electron.app",
@@ -58,11 +64,11 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
}
function isMachO(filePath) {
if (process.platform !== "darwin") {
if (hostPlatform !== "darwin") {
return true;
}
const result = spawnSync("file", ["-b", filePath], {
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
@@ -71,18 +77,18 @@ function isMachO(filePath) {
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !existsSync(runtimePath);
return !NodeFS.existsSync(runtimePath);
});
}
function invalidRuntimePaths(electronDir, platformPath) {
if (process.platform !== "darwin") {
if (hostPlatform !== "darwin") {
return [];
}
return [
join(electronDir, "dist", platformPath),
join(
NodePath.join(electronDir, "dist", platformPath),
NodePath.join(
electronDir,
"dist",
"Electron.app",
@@ -91,11 +97,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = spawnSync(command, args, {
const result = NodeChildProcess.spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
@@ -110,45 +116,45 @@ function runChecked(command, args) {
}
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
try {
runChecked("curl", [
"-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
"-o",
zipPath,
]);
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
if (hostPlatform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
join(electronDir, "dist"),
NodePath.join(electronDir, "dist"),
]);
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = NodePath.dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = join(electronDir, "dist", platformPath);
const electronPath = NodePath.join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
}
rmSync(join(electronDir, "path.txt"), { force: true });
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
+9 -8
View File
@@ -1,15 +1,16 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeChildProcess from "node:child_process";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, "..");
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
const child = spawn(electronBin, [mainJs], {
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+4 -3
View File
@@ -1,11 +1,12 @@
import { spawn } from "node:child_process";
import * as NodeChildProcess from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+8 -8
View File
@@ -1,13 +1,13 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodePath from "node:path";
import * as NodeTimersPromises from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
await NodeFSP.access(filePath);
return true;
} catch {
return false;
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
const socket = NodeNet.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
@@ -114,6 +114,6 @@ export async function waitForResources({
);
}
await Timers.setTimeout(intervalMs);
await NodeTimersPromises.setTimeout(intervalMs);
}
}
+63 -25
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
@@ -11,17 +11,20 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.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";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
@@ -32,22 +35,24 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
class DesktopBackendPortUnavailableError extends Data.TaggedError(
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
"DesktopBackendPortUnavailableError",
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
{
startPort: Schema.Int,
maxPort: Schema.Int,
hosts: Schema.Array(Schema.String),
},
) {
override get message(): string {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
"DesktopDevelopmentBackendPortRequiredError",
)<{}> {
override get message() {
{},
) {
override get message(): string {
return "T3CODE_PORT is required in desktop development.";
}
}
@@ -100,12 +105,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
): Effect.fn.Return<
void,
never,
| DesktopLifecycle.DesktopShutdown
| DesktopShutdown.DesktopShutdown
| DesktopState.DesktopState
| ElectronApp.ElectronApp
| ElectronDialog.ElectronDialog
> {
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const state = yield* DesktopState.DesktopState;
const electronApp = yield* ElectronApp.ElectronApp;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -132,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)) {
@@ -163,6 +171,16 @@ const bootstrap = Effect.gen(function* () {
}
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
const backendConfig = yield* serverExposure.backendConfig;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const rendererTarget = environment.isDevelopment
? Option.getOrThrow(environment.devServerUrl)
: backendConfig.httpBaseUrl;
yield* electronProtocol.registerDesktopProtocol({
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
targetOrigin: rendererTarget,
backendOrigin: backendConfig.httpBaseUrl,
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
});
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
@@ -176,12 +194,24 @@ const bootstrap = Effect.gen(function* () {
);
}
yield* installDesktopIpcHandlers;
yield* installDesktopIpcHandlers();
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"));
@@ -189,9 +219,8 @@ const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const updates = yield* DesktopUpdates.DesktopUpdates;
@@ -209,7 +238,7 @@ const startup = Effect.gen(function* () {
yield* appIdentity.configure;
yield* lifecycle.register;
yield* cloudAuth.configure;
yield* clerk.configure;
yield* electronApp.whenReady.pipe(
Effect.withSpan("desktop.electron.whenReady"),
@@ -218,7 +247,6 @@ const startup = Effect.gen(function* () {
yield* logStartupInfo("app ready");
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* electronProtocol.registerDesktopFileProtocol;
yield* updates.configure;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -229,11 +257,21 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const shutdown = yield* DesktopShutdown.DesktopShutdown;
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;
@@ -0,0 +1,30 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -4,6 +4,7 @@ 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 PlatformError from "effect/PlatformError";
import type * as Electron from "electron";
@@ -63,7 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronAppShape);
} satisfies ElectronApp.ElectronApp["Service"]);
const makeAssetsLayer = (png: Option.Option<string>) =>
Layer.succeed(DesktopAssets.DesktopAssets, {
@@ -73,7 +74,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
png,
}),
resolveResourcePath: () => Effect.succeed(Option.none()),
} satisfies DesktopAssets.DesktopAssetsShape);
} satisfies DesktopAssets.DesktopAssets["Service"]);
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
const { env, ...environmentOverrides } = overrides;
@@ -105,6 +106,7 @@ const withIdentity = <A, E, R>(
readonly calls?: ElectronAppCalls;
readonly environment?: TestEnvironmentInput;
readonly legacyPathExists?: boolean;
readonly legacyPathProbeError?: PlatformError.PlatformError;
readonly packageJson?: string;
readonly pngIconPath?: Option.Option<string>;
} = {},
@@ -121,7 +123,11 @@ const withIdentity = <A, E, R>(
Layer.provideMerge(
FileSystem.layerNoop({
exists: (path) =>
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
input.legacyPathProbeError
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}),
@@ -147,6 +153,33 @@ describe("DesktopAppIdentity", () => {
),
);
it.effect("preserves failures while inspecting the legacy userData path", () => {
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
description: "permission denied",
pathOrDescriptor: legacyPath,
});
return withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
assert.equal(error.legacyPath, legacyPath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
);
}),
{ legacyPathProbeError: cause },
);
});
it.effect("configures app identity from the environment commit override", () => {
const calls: ElectronAppCalls = {
setAboutPanelOptions: [],
+24 -8
View File
@@ -18,14 +18,24 @@ const AppPackageMetadata = Schema.Struct({
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
"DesktopUserDataPathResolutionError",
{
legacyPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
}
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
DesktopAppIdentityShape
{
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
readonly configure: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
@@ -35,7 +45,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -85,9 +95,15 @@ const make = Effect.gen(function* () {
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem
.exists(legacyPath)
.pipe(Effect.orElseSucceed(() => false));
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
@@ -0,0 +1,57 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
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.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
describe("DesktopAssets", () => {
it.effect("preserves the failed asset candidate and filesystem cause", () =>
Effect.gen(function* () {
const fileName = "custom.bin";
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
pathOrDescriptor: candidatePath,
description: "private filesystem diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
});
const assetsLayer = DesktopAssets.layer.pipe(
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
);
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
assert.equal(error.fileName, fileName);
assert.equal(error.candidatePath, candidatePath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
);
assert.notInclude(error.message, "private filesystem diagnostic");
}),
);
});
+42 -14
View File
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -12,27 +13,47 @@ export interface DesktopIconPaths {
readonly png: Option.Option<string>;
}
export interface DesktopAssetsShape {
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
"DesktopAssetProbeError",
{
fileName: Schema.String,
candidatePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
}
}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"@t3tools/desktop/app/DesktopAssets",
) {}
export class DesktopAssets extends Context.Service<
DesktopAssets,
{
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (
fileName: string,
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
fileName: string,
): Effect.fn.Return<
Option.Option<string>,
never,
DesktopAssetProbeError,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const candidates = environment.resolveResourcePathCandidates(fileName);
for (const candidate of candidates) {
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
const exists = yield* fileSystem
.exists(candidate)
.pipe(
Effect.mapError(
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
),
);
if (exists) {
return Option.some(candidate);
}
@@ -44,16 +65,23 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
Option.Option<string>,
never,
DesktopAssetProbeError,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
.pipe(Effect.orElseSucceed(() => false));
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
Effect.mapError(
(cause) =>
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
cause,
}),
),
);
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
}
@@ -62,7 +90,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
return yield* resolveResourcePath(`icon.${ext}`);
});
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>();
+149
View File
@@ -0,0 +1,149 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
storageAdapter: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
storageMock: vi.fn(),
}));
vi.mock("@clerk/electron", () => ({
createClerkBridge: createClerkBridgeMock,
}));
vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
);
};
describe("DesktopClerk", () => {
beforeEach(() => {
createClerkBridgeMock.mockReset();
storageMock.mockReset();
});
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
assert.equal(
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
"clerk.t3.codes",
);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
});
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme: "t3code-dev", host: "app" },
},
],
]);
assert.equal(cleanup.mock.calls.length, 1);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
it.effect("preserves bridge initialization failures", () => {
const cause = new Error("bridge initialization failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, true);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
);
});
});
it.effect("preserves bridge cleanup failures", () => {
const cause = new Error("bridge cleanup failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({
cleanup: () => {
throw cause;
},
});
return Effect.gen(function* () {
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
);
}
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
{
storage: storageAdapter,
passkeys: true,
renderer: { scheme, host: "app" },
},
],
]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
});
+135
View File
@@ -0,0 +1,135 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
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 Scope from "effect/Scope";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
"DesktopClerkBridgeInitializationError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
"DesktopClerkBridgeCleanupError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerk extends Context.Service<
DesktopClerk,
{
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
>()("@t3tools/desktop/app/DesktopClerk") {}
export function resolveDesktopClerkFrontendApiHostname(
publishableKey: string | undefined,
): string | undefined {
const normalizedKey = publishableKey?.trim();
if (!normalizedKey) return undefined;
try {
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
} catch {
return undefined;
}
}
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
passkeys: true,
renderer: {
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
host: ElectronProtocol.DESKTOP_HOST,
},
});
}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
new DesktopClerkBridgeInitializationError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}),
(bridge) =>
Effect.try({
try: () => bridge.cleanup(),
catch: (cause) =>
new DesktopClerkBridgeCleanupError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}).pipe(Effect.orDie),
);
return DesktopClerk.of({
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
yield* electronApp.on("second-instance", () => {
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
});
}).pipe(Effect.withSpan("desktop.clerk.configure")),
});
});
export const layer = Layer.effect(DesktopClerk, make);
@@ -1,302 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthHarness {
readonly app: ElectronApp.ElectronAppShape;
readonly window: ElectronWindow.ElectronWindowShape;
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
readonly protocolRegistrations: {
readonly protocol: string;
readonly path?: string;
readonly args?: readonly string[];
}[];
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
readonly reveals: unknown[];
readonly layer: Layer.Layer<
| DesktopCloudAuth.DesktopCloudAuth
| DesktopEnvironment.DesktopEnvironment
| ElectronApp.ElectronApp
| ElectronWindow.ElectronWindow
>;
}
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
const sends: CloudAuthHarness["sends"] = [];
const reveals: unknown[] = [];
const mainWindow = { id: "main-window" };
const app = ElectronApp.ElectronApp.of({
metadata: Effect.succeed({
appVersion: "0.0.0-test",
appPath: "/tmp/t3-code-test",
isPackaged: !input.isDevelopment,
resourcesPath: "/tmp/t3-code-test/resources",
runningUnderArm64Translation: false,
}),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
protocolRegistrations.push({
protocol,
...(path === undefined ? {} : { path }),
...(args === undefined ? {} : { args }),
});
return true;
}),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: (eventName, listener) =>
Effect.sync(() => {
const erasedListener = listener as (...args: readonly unknown[]) => void;
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
}),
});
const window = ElectronWindow.ElectronWindow.of({
create: () => Effect.die("not used"),
main: Effect.succeed(Option.some(mainWindow as never)),
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
reveal: (target) =>
Effect.sync(() => {
reveals.push(target);
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
sends.push({ channel, args });
}),
destroyAll: Effect.void,
syncAllAppearance: () => Effect.void,
});
const environment = DesktopEnvironment.DesktopEnvironment.of({
isDevelopment: input.isDevelopment,
} as DesktopEnvironment.DesktopEnvironmentShape);
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
return {
app,
window,
listeners,
protocolRegistrations,
sends,
reveals,
layer: Layer.mergeAll(
DesktopCloudAuth.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provide(NodeServices.layer),
),
Layer.succeed(ElectronApp.ElectronApp, app),
Layer.succeed(ElectronWindow.ElectronWindow, window),
),
};
}
function emitAppEvent(
harness: CloudAuthHarness,
eventName: string,
...args: readonly unknown[]
): void {
for (const listener of harness.listeners.get(eventName) ?? []) {
listener(...args);
}
}
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
describe("DesktopCloudAuth", () => {
it("uses separate callback schemes for packaged and development builds", () => {
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
"t3code",
);
assert.equal(
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
"t3code-dev",
);
});
it("builds a native callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code",
state: "state-1",
}),
"t3code://auth/callback?t3_state=state-1",
);
});
it("accepts only the expected scheme, host, path, and state", () => {
assert.isNotNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
scheme: "t3code",
state: "state-1",
}),
);
assert.isNull(
DesktopCloudAuth.parseCloudAuthCallbackUrl({
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
scheme: "t3code",
state: "state-1",
}),
);
});
it("builds a native development callback URL with request state", () => {
assert.equal(
DesktopCloudAuth.buildCloudAuthCallbackUrl({
scheme: "t3code-dev",
state: "state-1",
}),
"t3code-dev://auth/callback?t3_state=state-1",
);
});
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
let prevented = false;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => (prevented = true) },
callbackUrl.toString(),
);
yield* flushCloudAuthDispatch;
assert.isTrue(prevented);
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code-dev"],
);
assert.isString(harness.protocolRegistrations[0]?.path);
assert.isArray(harness.protocolRegistrations[0]?.args);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.lengthOf(harness.reveals, 1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
const harness = makeHarness({ isDevelopment: false });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const validCallback = new URL(redirectUrl);
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
const invalidCallback = new URL(validCallback);
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
invalidCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, []);
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
emitAppEvent(
harness,
"open-url",
{ preventDefault: () => undefined },
validCallback.toString(),
);
yield* flushCloudAuthDispatch;
assert.deepEqual(
harness.protocolRegistrations.map((registration) => registration.protocol),
["t3code"],
);
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [validCallback.toString()],
},
]);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
});
it.effect(
"routes second-instance callbacks and reveals the window for non-callback launches",
() => {
const harness = makeHarness({ isDevelopment: true });
return Effect.gen(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
yield* cloudAuth.configure;
const redirectUrl = yield* cloudAuth.createRequest;
const callbackUrl = new URL(redirectUrl);
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
yield* flushCloudAuthDispatch;
const revealCountAfterCallback = harness.reveals.length;
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
yield* flushCloudAuthDispatch;
assert.deepEqual(harness.sends, [
{
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
args: [callbackUrl.toString()],
},
]);
assert.equal(revealCountAfterCallback, 1);
assert.equal(harness.reveals.length, 2);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
},
);
});
-330
View File
@@ -1,330 +0,0 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import type * as Electron from "electron";
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
"DesktopCloudAuthCallbackServerError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to start the desktop cloud auth callback server.";
}
}
interface PendingCloudAuthRequest {
readonly state: string;
readonly redirectUrl: string;
readonly close: () => void;
}
export interface DesktopCloudAuthShape {
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
readonly configure: Effect.Effect<
void,
never,
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
>;
}
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
"@t3tools/desktop/app/DesktopCloudAuth",
) {}
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
}
export function buildCloudAuthCallbackUrl(input: {
readonly scheme: string;
readonly state: string;
}): string {
const url = new URL(
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
);
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
return url.toString();
}
export function parseCloudAuthCallbackUrl(input: {
readonly rawUrl: unknown;
readonly scheme: string;
readonly state: string;
}): URL | null {
if (typeof input.rawUrl !== "string") {
return null;
}
try {
const url = new URL(input.rawUrl);
if (url.protocol !== `${input.scheme}:`) return null;
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
return url;
} catch {
return null;
}
}
export function findCloudAuthCallbackUrl(input: {
readonly values: readonly unknown[];
readonly scheme: string;
readonly state: string;
}): URL | null {
for (const value of input.values) {
const url = parseCloudAuthCallbackUrl({
rawUrl: value,
scheme: input.scheme,
state: input.state,
});
if (url) return url;
}
return null;
}
export function resolveProtocolClientLaunchArgs(input: {
readonly argv: readonly string[];
}): readonly string[] {
return input.argv.slice(1);
}
function resolveConfiguredProtocolClient(): {
readonly path: string;
readonly args: readonly string[];
} | null {
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
if (!path) return null;
return {
path,
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
.split("\n")
.map((arg) => arg.trim())
.filter((arg) => arg.length > 0),
};
}
function isProtocolRegistrationManagedExternally(): boolean {
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
}
function resolveProtocolCallbackForwardUrl(): URL | null {
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
if (!rawUrl) return null;
try {
const url = new URL(rawUrl);
if (url.protocol !== "http:") return null;
if (url.hostname !== "127.0.0.1") return null;
if (url.pathname !== "/auth/callback") return null;
if (!url.port) return null;
return url;
} catch {
return null;
}
}
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
request?.close();
return null;
};
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
}
function ignoreCloudAuthCallback(_rawUrl: string) {}
function startProtocolCallbackForwardServer(
callbackUrl: URL,
dispatch: (rawUrl: string) => void,
): Effect.Effect<void, never, Scope.Scope> {
const port = Number.parseInt(callbackUrl.port, 10);
const routesLayer = HttpRouter.add(
"POST",
"/auth/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const rawUrl = yield* request.text;
yield* Effect.sync(() => {
dispatch(rawUrl);
});
return HttpServerResponse.empty({ status: 204 });
}),
);
return Effect.gen(function* () {
const NodeHttp = yield* Effect.promise(() => import("node:http"));
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
host: callbackUrl.hostname,
port,
});
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
Effect.forkScoped,
);
});
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
const makeCloudAuthRequestState = Effect.gen(function* () {
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
return `${left}${right}`.replaceAll("-", "");
});
return DesktopCloudAuth.of({
createRequest: Effect.gen(function* () {
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
const state = yield* makeCloudAuthRequestState.pipe(
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
);
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
const timeout = createCloudAuthRequestTimeout(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
});
pendingAuthRequest = {
state,
redirectUrl,
close: () => clearTimeout(timeout),
};
return redirectUrl;
}),
configure: Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const scope = yield* Scope.Scope;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const scheme = resolveCloudAuthCallbackScheme({
isDevelopment: environment.isDevelopment,
});
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
}),
);
if (isProtocolRegistrationManagedExternally()) {
// Development macOS launchers set the default URL handler before the stock Electron
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
} else if (environment.isDevelopment) {
const configuredClient = resolveConfiguredProtocolClient();
if (configuredClient) {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
configuredClient.path,
configuredClient.args,
);
} else {
yield* electronApp.setAsDefaultProtocolClient(
scheme,
process.execPath,
resolveProtocolClientLaunchArgs({ argv: process.argv }),
);
}
} else {
yield* electronApp.setAsDefaultProtocolClient(scheme);
}
dispatchCloudAuthCallback = (rawUrl: string) => {
const pending = pendingAuthRequest;
const callbackUrl = pending
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
: null;
if (!callbackUrl) {
return;
}
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
void runPromise(
Effect.gen(function* () {
yield* electronWindow.sendAll(
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
callbackUrl.toString(),
);
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
};
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
if (environment.isDevelopment && protocolCallbackForwardUrl) {
yield* startProtocolCallbackForwardServer(
protocolCallbackForwardUrl,
dispatchCloudAuthCallback,
);
}
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
if (!hasInstanceLock) {
return yield* electronApp.quit;
}
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
event.preventDefault?.();
dispatchCloudAuthCallback(rawUrl);
});
yield* electronApp.on<[Electron.Event, readonly string[]]>(
"second-instance",
(_event, argv) => {
const values = resolveProtocolClientLaunchArgs({ argv });
const pending = pendingAuthRequest;
const callbackUrl = pending
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
: null;
if (callbackUrl) {
dispatchCloudAuthCallback(callbackUrl.toString());
return;
}
void runPromise(
Effect.gen(function* () {
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
}
}),
);
},
);
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
});
});
export const layer = Layer.effect(DesktopCloudAuth, make);
@@ -1,96 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
function makeSafeStorageLayer(input: { readonly available: boolean }) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(input.available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
decryptString: (value) => {
const decoded = textDecoder.decode(value);
if (!decoded.startsWith("enc:")) {
return Effect.fail(
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted token"),
}),
);
}
return Effect.succeed(decoded.slice("enc:".length));
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopCloudAuthTokenStore.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
Layer.provideMerge(NodeServices.layer),
);
}
const withTokenStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
input?: { readonly encryptionAvailable?: boolean },
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-cloud-auth-token-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopCloudAuthTokenStore", () => {
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
yield* tokenStore.clear;
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
),
);
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
withTokenStore(
Effect.gen(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
}),
{ encryptionAvailable: false },
),
);
});
@@ -1,155 +0,0 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
interface CloudAuthTokenDocument {
readonly version: number;
readonly encryptedClientJwt: string;
}
const CloudAuthTokenDocumentSchema = Schema.Struct({
version: Schema.Number,
encryptedClientJwt: Schema.String,
});
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
}
}
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
"DesktopCloudAuthTokenStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode desktop cloud auth token.";
}
}
export interface DesktopCloudAuthTokenStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopCloudAuthTokenStoreDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
token: string,
) => Effect.Effect<
boolean,
| DesktopCloudAuthTokenStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopCloudAuthTokenStore extends Context.Service<
DesktopCloudAuthTokenStore,
DesktopCloudAuthTokenStoreShape
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
tokenPath: string,
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
fileSystem.readFileString(tokenPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
}),
),
);
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly tokenPath: string;
readonly document: CloudAuthTokenDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.tokenPath);
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.tokenPath);
});
export const layer = Layer.effect(
DesktopCloudAuthTokenStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
return DesktopCloudAuthTokenStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, tokenPath);
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
tokenPath,
document: { version: 1, encryptedClientJwt },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
return true;
}),
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
Effect.catch(() => Effect.void),
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
),
});
}),
);
@@ -0,0 +1,415 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
);
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the failed catalog write operation and path", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
makeDirectory: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.set("{}").pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("reports the legacy migration stage", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
);
assert.equal(error.operation, "read-legacy-registry");
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
assert.instanceOf(
error.cause,
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
);
const registryError =
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
assert.exists(registryError.cause);
assert.equal(
error.message,
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
);
assert.notEqual(error.message, registryError.message);
}),
),
);
it.effect("reports invalid encrypted catalog data without exposing it", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
);
assert.equal(error.resource, "encryptedCatalog");
assert.equal(error.catalogPath, catalogPath);
assert.exists(error.cause);
assert.equal(
error.message,
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
);
assert.notInclude(error.message, "%%%");
}),
),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
);
assert.equal(error.operation, "decrypt-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
assert.instanceOf(decryptError.cause, Error);
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
assert.equal(
error.message,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, decryptError.message);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -0,0 +1,516 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
"encode-document",
"create-directory",
"write-temporary-file",
"replace-catalog-file",
]);
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
"read-legacy-secret",
"encode-catalog",
"persist-catalog",
]);
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"DesktopConnectionCatalogStoreWriteError",
{
operation: DesktopConnectionCatalogStoreWriteOperation,
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"DesktopConnectionCatalogStoreDecodeError",
{
resource: Schema.Literal("encryptedCatalog"),
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
"DesktopConnectionCatalogStoreReadError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
"DesktopConnectionCatalogStoreDocumentDecodeError",
{
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
"DesktopConnectionCatalogStoreMigrationError",
{
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: Schema.String,
environmentId: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const environment =
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
"DesktopConnectionCatalogStoreProtectionError",
{
operation: DesktopConnectionCatalogStoreProtectionOperation,
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
{
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| DesktopConnectionCatalogStoreProtectionError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
>;
readonly clear: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
catalogPath: string,
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDecodeError({
resource: "encryptedCatalog",
catalogPath,
cause,
}),
),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound"
? Effect.succeed<string | null>(null)
: Effect.fail(
new DesktopConnectionCatalogStoreReadError({
catalogPath,
cause: error,
}),
),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
Effect.map(Option.some),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreDocumentDecodeError({
catalogPath,
cause,
}),
),
),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "encode-document",
path: input.catalogPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "replace-catalog-file",
path: input.catalogPath,
cause,
}),
),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
catalogPath: string,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopConnectionCatalogStoreMigrationError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-secret",
catalogPath,
environmentId: record.environmentId,
cause,
}),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "check-encryption-availability",
catalogPath,
cause,
}),
),
);
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(
yield* safeStorage.encryptString(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "encrypt-catalog",
catalogPath,
cause,
}),
),
),
);
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
});
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-registry",
catalogPath,
cause,
}),
),
);
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "encode-catalog",
catalogPath,
cause,
}),
),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "persist-catalog",
catalogPath,
cause,
}),
),
);
return Option.some(encoded);
});
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "decrypt-catalog",
catalogPath,
cause,
}),
),
),
),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
});
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
@@ -0,0 +1,37 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
describe("desktop detached action errors", () => {
it("preserves the complete relaunch failure cause and reason", () => {
const cause = Cause.combine(
Cause.fail(new Error("shutdown failed")),
Cause.die(new Error("relaunch defect")),
);
const error = new DesktopLifecycleRelaunchError({
reason: "apply update",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "apply update");
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
});
it("preserves the complete menu action failure cause and action", () => {
const cause = Cause.combine(
Cause.fail(new Error("window unavailable")),
Cause.die(new Error("dispatch defect")),
);
const error = new DesktopApplicationMenuActionError({
action: "open-settings",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.action, "open-settings");
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
});
});
@@ -53,12 +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.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");
@@ -77,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(
{},
@@ -89,10 +93,24 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
}),
);
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(
+57 -56
View File
@@ -11,10 +11,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import {
type DesktopSettings,
resolveDefaultDesktopSettings,
} from "../settings/DesktopAppSettings.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
@@ -30,54 +27,53 @@ export interface MakeDesktopEnvironmentInput {
readonly runningUnderArm64Translation: boolean;
}
export interface DesktopEnvironmentShape {
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
DesktopEnvironmentShape
{
readonly path: Path.Path;
readonly dirname: string;
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly isPackaged: boolean;
readonly isDevelopment: boolean;
readonly appVersion: string;
readonly appPath: string;
readonly resourcesPath: string;
readonly homeDirectory: string;
readonly appDataDirectory: string;
readonly baseDir: string;
readonly stateDir: string;
readonly desktopSettingsPath: string;
readonly clientSettingsPath: string;
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
readonly configuredBackendPort: Option.Option<number>;
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
>()("@t3tools/desktop/app/DesktopEnvironment") {}
const APP_BASE_NAME = "T3 Code";
@@ -135,9 +131,9 @@ function resolveDesktopRuntimeInfo(input: {
};
}
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
const make = Effect.fn("desktop.environment.make")(function* (
input: MakeDesktopEnvironmentInput,
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
const path = yield* Path.Path;
const config = yield* DesktopConfig.DesktopConfig;
const homeDirectory = input.homeDirectory;
@@ -151,7 +147,8 @@ const makeDesktopEnvironment = 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({
@@ -159,7 +156,10 @@ const makeDesktopEnvironment = 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;
@@ -183,6 +183,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
serverSettingsPath: path.join(stateDir, "settings.json"),
logDir: path.join(stateDir, "logs"),
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
@@ -206,7 +207,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
runtimeInfo: resolveDesktopRuntimeInfo({
platform: input.platform,
processArch: input.processArch,
@@ -248,4 +249,4 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
});
export const layer = (input: MakeDesktopEnvironmentInput) =>
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
Layer.effect(DesktopEnvironment, make(input));
+108 -124
View File
@@ -1,75 +1,55 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
export interface DesktopShutdownShape {
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
"DesktopLifecycleRelaunchError",
{
reason: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop relaunch failed for reason "${this.reason}".`;
}
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
) {}
const makeShutdown = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown
| DesktopShutdown.DesktopShutdown
| DesktopState.DesktopState
| DesktopWindow.DesktopWindow
| ElectronApp.ElectronApp
| ElectronTheme.ElectronTheme;
export interface DesktopLifecycleShape {
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"@t3tools/desktop/app/DesktopLifecycle",
) {}
export class DesktopLifecycle extends Context.Service<
DesktopLifecycle,
{
readonly relaunch: (
reason: string,
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
>()("@t3tools/desktop/app/DesktopLifecycle") {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
DesktopObservability.makeComponentLogger("desktop-lifecycle");
makeComponentLogger("desktop-lifecycle");
function addScopedListener<Args extends ReadonlyArray<unknown>>(
target: unknown,
@@ -93,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
const shutdown = yield* 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;
},
@@ -154,83 +140,81 @@ function quitFromSignal(
);
}
export const layer = Layer.succeed(
DesktopLifecycle,
DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
}
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
}),
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
export const make = DesktopLifecycle.of({
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const state = yield* DesktopState.DesktopState;
yield* logLifecycleInfo("desktop relaunch requested", { reason });
yield* Effect.gen(function* () {
yield* Effect.yieldNow;
yield* Ref.set(state.quitting, true);
yield* requestDesktopShutdownAndWait();
if (environment.isDevelopment) {
yield* electronApp.exit(75);
return;
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
yield* electronApp.relaunch({
execPath: process.execPath,
args: process.argv.slice(1),
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
Effect.forkDetach,
Effect.asVoid,
);
}),
);
register: Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronApp = yield* ElectronApp.ElectronApp;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
const runEffect = Effect.runPromiseWith(context);
let quitAllowed = false;
yield* electronTheme.onUpdated(() => {
void runEffect(
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
);
});
yield* electronApp.on("before-quit", (event: Electron.Event) => {
handleBeforeQuit(
event,
runEffect,
() => quitAllowed,
() => {
quitAllowed = true;
},
);
});
yield* electronApp.on("activate", () => {
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
});
yield* electronApp.on("window-all-closed", () => {
void runEffect(
Effect.gen(function* () {
const app = yield* ElectronApp.ElectronApp;
const state = yield* DesktopState.DesktopState;
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
yield* app.quit;
}
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
);
});
if (environment.platform !== "win32") {
yield* addScopedListener(process, "SIGINT", () => {
quitFromSignal("SIGINT", runEffect);
});
yield* addScopedListener(process, "SIGTERM", () => {
quitFromSignal("SIGTERM", runEffect);
});
}
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
});
export const layer = Layer.succeed(DesktopLifecycle, make);
@@ -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(
+138 -44
View File
@@ -1,7 +1,7 @@
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 Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -13,7 +13,9 @@ 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";
@@ -40,10 +42,21 @@ export interface DesktopBackendOutputLogShape {
) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
// 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();
@@ -82,12 +95,13 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
)<{
readonly option: "maxBytes" | "maxFiles";
readonly value: number;
}> {
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message() {
return `${this.option} must be >= 1 (received ${this.value})`;
}
@@ -293,22 +307,51 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
},
);
const backendOutputLogLayer = Layer.effect(
DesktopBackendOutputLog,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
return Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn(
"desktop.observability.backendOutput.writeSessionBoundary",
)(function* ({ phase, details }) {
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()}`,
@@ -316,30 +359,81 @@ const backendOutputLogLayer = Layer.effect(
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;
}),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
);
});
return DesktopBackendOutputLogFactory.of({
forInstance: (id) => makeForId(id),
});
}),
);
@@ -387,7 +481,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
backendOutputLogLayer,
backendOutputLogFactoryLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
+35
View File
@@ -0,0 +1,35 @@
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
export class DesktopShutdown extends Context.Service<
DesktopShutdown,
{
readonly request: Effect.Effect<void>;
readonly awaitRequest: Effect.Effect<void>;
readonly markComplete: Effect.Effect<void>;
readonly awaitComplete: Effect.Effect<void>;
readonly isComplete: Effect.Effect<boolean>;
}
>()("@t3tools/desktop/app/DesktopShutdown") {}
const make = Effect.gen(function* () {
const requested = yield* Deferred.make<void>();
const completed = yield* Deferred.make<void>();
const completedRef = yield* Ref.make(false);
return DesktopShutdown.of({
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
awaitRequest: Deferred.await(requested),
markComplete: Ref.set(completedRef, true).pipe(
Effect.andThen(Deferred.succeed(completed, undefined)),
Effect.asVoid,
),
awaitComplete: Deferred.await(completed),
isComplete: Ref.get(completedRef),
});
});
export const layer = Layer.effect(DesktopShutdown, make);
+13 -15
View File
@@ -3,19 +3,17 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
export interface DesktopStateShape {
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"@t3tools/desktop/app/DesktopState",
) {}
export const layer = Layer.effect(
export class DesktopState extends Context.Service<
DesktopState,
Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
}),
);
{
readonly backendReady: Ref.Ref<boolean>;
readonly quitting: Ref.Ref<boolean>;
}
>()("@t3tools/desktop/app/DesktopState") {}
const make = Effect.all({
backendReady: Ref.make(false),
quitting: Ref.make(false),
});
export const layer = Layer.effect(DesktopState, make);
@@ -3,12 +3,20 @@ 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 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({
@@ -21,6 +29,10 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
);
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
);
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
@@ -34,24 +46,27 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposureShape);
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
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(
@@ -69,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,
@@ -89,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)),
),
),
@@ -96,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);
@@ -127,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;
@@ -147,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);
@@ -166,7 +351,66 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("captures backend output in development so child process logs can be persisted", () =>
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 = path.join(baseDir, "userdata", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: settingsPath,
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const failingFileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(cause),
}),
);
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
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),
),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
const error = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.find(isDesktopBackendObservabilitySettingsReadError);
assert.isDefined(error);
assert.equal(error.settingsPath, settingsPath);
assert.equal(error.cause, cause);
assert.equal(
error.message,
`Failed to read persisted backend observability settings at ${settingsPath}.`,
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
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({
@@ -175,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,
@@ -192,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,23 +9,58 @@ 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 DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
{
settingsPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
}
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
DesktopBackendConfigurationShape
{
// 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") {}
interface BackendObservabilitySettings {
@@ -49,32 +86,76 @@ 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 { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
const getWslEnvEntryName = (entry: string): string => {
const slashIndex = entry.indexOf("/");
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
};
const readPersistedBackendObservabilitySettings: Effect.Effect<
BackendObservabilitySettings,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
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,
) => {
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
return Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-backend-configuration",
error,
}),
);
};
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const exists = yield* fileSystem
.exists(environment.serverSettingsPath)
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return emptyBackendObservabilitySettings;
}
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
Effect.as(Option.none()),
),
}),
);
if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings;
}
@@ -85,11 +166,168 @@ const readPersistedBackendObservabilitySettings: Effect.Effect<
};
});
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
@@ -98,72 +336,351 @@ 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;
},
);
export const layer = Layer.effect(
DesktopBackendConfiguration,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
const 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;
// 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;
}),
),
}),
);
// 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({
resolvePrimary: Effect.gen(function* () {
const { useWsl, wslRequested } = yield* describePrimary;
if (useWsl) {
return yield* buildWslPrimaryConfig;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
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),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
});
}),
);
}).pipe(
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
attributes: { port: input.port, distro: input.distro ?? null },
}),
),
});
});
export const layer = Layer.effect(DesktopBackendConfiguration, make);
@@ -20,10 +20,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
@@ -31,6 +28,7 @@ const decodeDesktopBackendBootstrap = Schema.decodeEffect(
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
entryPath: "/server/bin.mjs",
cwd: "/server",
env: { ELECTRON_RUN_AS_NODE: "1" },
@@ -44,8 +42,11 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
bootstrapDelivery: "fd3",
extendEnv: true,
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
preflightFailure: Option.none(),
};
const configWithObservability: DesktopBackendBootstrapValue = {
@@ -101,97 +102,98 @@ function decodeBootstrap(raw: string) {
return decodeDesktopBackendBootstrap(raw);
}
function makeManagerLayer(input: {
interface MakeInstanceInput {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
readonly onReady?: Effect.Effect<void>;
readonly onShutdown?: Effect.Effect<void>;
readonly onPreflightFailed?: (
failure: DesktopBackendManager.PreflightFailure,
) => Effect.Effect<boolean>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) {
return DesktopBackendManager.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolve: Effect.succeed(input.config ?? baseConfig),
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
input.desktopState
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
: DesktopState.layer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
handleBackendReady: Effect.void,
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
...input.desktopWindow,
} satisfies DesktopWindow.DesktopWindowShape),
),
),
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
// Helper that constructs a primary backend instance using the factory
// directly. The factory's deps (FileSystem, ChildProcessSpawner,
// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
// to drive the instance's lifecycle.
function makeTestInstance(input: MakeInstanceInput) {
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
};
const servicesLayer = Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () => Effect.succeed(stubLog),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
);
const instance = DesktopBackendManager.makeBackendInstance({
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
label: Effect.succeed("Windows"),
configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
...(input.onReady ? { onReady: () => input.onReady! } : {}),
...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
});
return instance.pipe(Effect.provide(servicesLayer));
}
describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
Effect.scoped(
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
spawnedCommand = command;
if (command._tag === "StandardCommand") {
const fd3 = command.options.additionalFds?.fd3;
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
spawnedCommand = command;
if (command._tag === "StandardCommand") {
const fd3 = command.options.additionalFds?.fd3;
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
}
}
return makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
return makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const managerLayer = makeManagerLayer({
config: {
...baseConfig,
bootstrap: configWithObservability,
},
spawnerLayer,
desktopWindow: {
handleBackendReady: Effect.sync(() => {
const instance = yield* makeTestInstance({
config: {
...baseConfig,
bootstrap: configWithObservability,
},
spawnerLayer,
onReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* instance.start;
yield* Queue.take(exited);
assert.equal(readyCount, 1);
@@ -214,55 +216,52 @@ describe("DesktopBackendManager", () => {
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
}).pipe(Effect.provide(managerLayer));
}),
}),
),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
const statuses = [503, 200];
let readyCount = 0;
const firstRequest = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
Effect.scoped(
Effect.gen(function* () {
const requestUrls: Array<string> = [];
const statuses = [503, 200];
let readyCount = 0;
const firstRequest = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer((request) =>
Effect.gen(function* () {
const status = statuses.shift();
assert.isDefined(status);
requestUrls.push(request.url);
yield* Deferred.succeed(firstRequest, void 0);
return responseForRequest(request, status);
}),
),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer((request) =>
Effect.gen(function* () {
const status = statuses.shift();
assert.isDefined(status);
requestUrls.push(request.url);
yield* Deferred.succeed(firstRequest, void 0);
return responseForRequest(request, status);
}),
),
desktopWindow: {
handleBackendReady: Effect.sync(() => {
onReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* instance.start;
yield* Deferred.await(firstRequest);
assert.equal(readyCount, 0);
@@ -276,106 +275,136 @@ describe("DesktopBackendManager", () => {
"http://127.0.0.1:3773/.well-known/t3/environment",
"http://127.0.0.1:3773/.well-known/t3/environment",
]);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("starts the configured backend and closes the scoped process on stop", () =>
Effect.gen(function* () {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReady = yield* Ref.make(false);
const quitting = yield* Ref.make(false);
Effect.scoped(
Effect.gen(function* () {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReadyFlag = yield* Ref.make(false);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
desktopState: {
backendReady,
quitting,
},
desktopWindow: {
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
},
});
const instance = yield* makeTestInstance({
spawnerLayer,
onReady: Ref.set(backendReadyFlag, true).pipe(
Effect.andThen(Deferred.succeed(ready, void 0)),
Effect.asVoid,
),
onShutdown: Ref.set(backendReadyFlag, false),
});
assert.isTrue(Option.isNone(yield* instance.currentConfig));
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
assert.isTrue(Option.isNone(yield* manager.currentConfig));
yield* manager.start;
yield* instance.start;
assert.equal(yield* Queue.take(startedPids), 123);
yield* Deferred.await(ready);
assert.isTrue(yield* Ref.get(backendReady));
assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
assert.isTrue(yield* Ref.get(backendReadyFlag));
assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
const runningSnapshot = yield* manager.snapshot;
const runningSnapshot = yield* instance.snapshot;
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
yield* manager.stop();
yield* instance.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
const stoppedSnapshot = yield* manager.snapshot;
assert.isFalse(yield* Ref.get(backendReady));
const stoppedSnapshot = yield* instance.snapshot;
assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
}).pipe(Effect.provide(managerLayer));
}),
}),
),
);
it.effect("does not notify shutdown before the first start has prior state", () =>
Effect.scoped(
Effect.gen(function* () {
let shutdownCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Queue.offer(startedPids, 123);
const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
onShutdown: Effect.sync(() => {
shutdownCount += 1;
}),
});
yield* instance.start;
assert.equal(yield* Queue.take(startedPids), 123);
assert.equal(shutdownCount, 0);
}),
),
);
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
@@ -388,107 +417,300 @@ describe("DesktopBackendManager", () => {
assert.equal(yield* Queue.size(starts), 0);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(yield* Queue.take(starts), 3);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
Effect.scoped(
Effect.gen(function* () {
let shutdownCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
},
onShutdown: Effect.sync(() => {
shutdownCount += 1;
}),
});
yield* instance.start;
assert.equal(shutdownCount, 0);
yield* TestClock.adjust(Duration.millis(500));
assert.equal(shutdownCount, 0);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
assert.deepEqual(failures, []);
// Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
// the cap, at which point the failure is surfaced exactly once.
yield* TestClock.adjust(Duration.millis(500));
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.adjust(Duration.seconds(2));
yield* TestClock.adjust(Duration.seconds(4));
assert.deepEqual(failures, ["Node.js not found"]);
// Past the cap the loop stops and nothing else is surfaced.
yield* TestClock.adjust(Duration.seconds(8));
yield* TestClock.adjust(Duration.seconds(30));
assert.deepEqual(failures, ["Node.js not found"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("can be started again after a fatal preflight cap once config recovers", () =>
Effect.scoped(
Effect.gen(function* () {
const failing = yield* Ref.make(true);
const starts = yield* Queue.unbounded<number>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Queue.offer(starts, 123).pipe(
Effect.as(
makeProcess({
exitCode: Effect.never,
}),
),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
configResolve: Ref.get(failing).pipe(
Effect.map((isFailing) =>
isFailing
? {
...baseConfig,
preflightFailure: Option.some({
reason: "Node.js not found",
fatal: true,
}),
}
: baseConfig,
),
),
});
yield* instance.start;
yield* TestClock.adjust(Duration.millis(500));
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.adjust(Duration.seconds(2));
yield* TestClock.adjust(Duration.seconds(4));
yield* TestClock.adjust(Duration.seconds(8));
const parked = yield* instance.snapshot;
assert.equal(parked.desiredRunning, false);
assert.equal(parked.ready, false);
assert.isTrue(Option.isNone(parked.activePid));
assert.equal(parked.restartScheduled, false);
assert.equal(yield* Queue.size(starts), 0);
yield* Ref.set(failing, false);
yield* instance.start;
assert.equal(yield* Queue.take(starts), 123);
const running = yield* instance.snapshot;
assert.equal(running.desiredRunning, true);
assert.deepEqual(running.activePid, Option.some(123));
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
// Well beyond the fatal cap's worth of time: a transient failure must
// keep retrying (self-heal) and never surface.
yield* TestClock.adjust(Duration.minutes(2));
assert.deepEqual(failures, []);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({
reason: "WSL toolchain probe timed out",
fatal: false,
retryLimit: 3,
}),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
yield* TestClock.adjust(Duration.millis(500));
assert.deepEqual(failures, []);
yield* TestClock.adjust(Duration.seconds(1));
assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("cancels a scheduled restart when start is requested manually", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const secondClosed = yield* Deferred.make<void>();
let startCount = 0;
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const secondClosed = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
startCount += 1;
yield* Queue.offer(starts, startCount);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
if (startCount === 1) {
return makeProcess({
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
});
}
const scope = yield* Scope.Scope;
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
exitCode: Deferred.await(secondClosed).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
kill: () => close,
});
}
}),
),
);
const scope = yield* Scope.Scope;
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(secondClosed).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
kill: () => close,
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
yield* manager.start;
yield* instance.start;
assert.equal(yield* Queue.take(starts), 2);
yield* manager.stop();
yield* instance.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("does not restart after stop cancels a scheduled restart", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* manager.snapshot).restartScheduled;
restartScheduled = (yield* instance.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* manager.stop();
yield* instance.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
assert.equal((yield* manager.snapshot).desiredRunning, false);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
assert.equal((yield* instance.snapshot).desiredRunning, false);
}).pipe(Effect.provide(TestClock.layer())),
),
);
});
+309 -96
View File
@@ -1,12 +1,35 @@
// 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 Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
@@ -22,15 +45,19 @@ 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);
@@ -43,14 +70,37 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
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;
}
// 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 {
@@ -59,29 +109,38 @@ interface BackendProcessExit {
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
readonly url: URL;
}> {
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
url: Schema.instanceOf(URL),
},
) {
override get message() {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
)<{
readonly cause: Schema.SchemaError;
}> {
{
entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
readonly cause: PlatformError.PlatformError;
}> {
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to spawn desktop backend process: ${this.cause.message}`;
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
}
}
@@ -106,20 +165,60 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
export interface DesktopBackendManagerShape {
// 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>();
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>;
}
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
DesktopBackendManagerShape
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
// 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;
@@ -134,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;
}
@@ -144,6 +246,7 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -176,23 +279,20 @@ const closeRun = (
).pipe(Effect.ignore);
};
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
const waitForHttpReady = (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
);
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
);
});
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 }),
});
};
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
@@ -230,35 +330,38 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
Effect.mapError(
(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({ cause })));
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
@@ -277,18 +380,34 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(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));
@@ -328,10 +447,15 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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", {
logInstanceError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
@@ -344,14 +468,84 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
.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;
@@ -372,7 +566,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
},
]);
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
@@ -424,7 +618,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
details: `pid=${pid.value} ${reason}`,
});
}
yield* Ref.set(desktopState.backendReady, false);
yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -436,7 +630,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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),
@@ -446,7 +640,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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) {
@@ -466,17 +660,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
return;
}
yield* Ref.set(desktopState.backendReady, true);
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
message: error.message,
}),
),
);
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
logInstanceWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
@@ -498,9 +685,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}));
}),
),
).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) => {
@@ -520,8 +707,8 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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),
});
@@ -541,7 +728,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) =>
logBackendManagerError("desktop backend restart fiber failed", {
logInstanceError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
@@ -560,7 +747,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
});
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)(
@@ -578,7 +765,15 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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;
}),
);
@@ -593,14 +788,32 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
});
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, makeDesktopBackendManager());
@@ -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"),
});
}),
);
@@ -0,0 +1,81 @@
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 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 DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
env: {},
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3773,
t3Home: "/tmp/t3",
host: "127.0.0.1",
desktopBootstrapToken: "desktop-bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
};
describe("DesktopLocalEnvironmentAuth", () => {
it.effect("exchanges the desktop bootstrap credential only once", () =>
Effect.gen(function* () {
const requestCount = yield* Ref.make(0);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.update(requestCount, (count) => count + 1).pipe(
Effect.as(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
),
),
);
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(poolLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
}).pipe(Effect.provide(testLayer));
assert.strictEqual(first, "desktop-bearer-token");
assert.strictEqual(second, "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}),
);
});
@@ -0,0 +1,95 @@
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";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
{},
) {
override get message(): string {
return "Local backend is not configured.";
}
}
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
"DesktopLocalEnvironmentAuthSessionBootstrapError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to create the local desktop bearer session.";
}
}
export const DesktopLocalEnvironmentAuthError = Schema.Union([
DesktopLocalEnvironmentAuthBackendNotConfiguredError,
DesktopLocalEnvironmentAuthSessionBootstrapError,
]);
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
export class DesktopLocalEnvironmentAuth extends Context.Service<
DesktopLocalEnvironmentAuth,
{
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
}
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
const getBearerToken = mutex
.withPermits(1)(
Effect.gen(function* () {
const cached = yield* Ref.get(tokenRef);
if (Option.isSome(cached)) {
return cached.value;
}
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,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
},
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.mapError(
(cause) =>
new DesktopLocalEnvironmentAuthSessionBootstrapError({
cause,
}),
),
);
yield* Ref.set(tokenRef, Option.some(session.access_token));
return session.access_token;
}),
)
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
});
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
@@ -0,0 +1,65 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { networkInterfacesMock } = vi.hoisted(() => ({
networkInterfacesMock: vi.fn(),
}));
vi.mock("node:os", () => ({
networkInterfaces: networkInterfacesMock,
}));
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("DesktopNetworkInterfaces", () => {
beforeEach(() => {
networkInterfacesMock.mockReset();
});
it.effect("reads network interfaces through the service", () => {
const interfaces = {
en0: [
{
address: "192.168.1.10",
family: "IPv4",
internal: false,
},
],
};
networkInterfacesMock.mockReturnValueOnce(interfaces);
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
assert.strictEqual(yield* service.read, interfaces);
}).pipe(Effect.provide(TestLayer));
});
it.effect("preserves network interface read failures as structured defects", () => {
const cause = new Error("network interface probe failed");
networkInterfacesMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const exit = yield* Effect.exit(service.read);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
assert.equal(error.platform, "linux");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
}
}).pipe(Effect.provide(TestLayer));
});
});
@@ -0,0 +1,52 @@
import * as NodeOS from "node:os";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type NetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
"DesktopNetworkInterfacesReadError",
{
platform: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop network interfaces on ${this.platform}.`;
}
}
export class DesktopNetworkInterfaces extends Context.Service<
DesktopNetworkInterfaces,
{
readonly read: Effect.Effect<NetworkInterfaces>;
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return DesktopNetworkInterfaces.of({
read: Effect.try({
try: () => NodeOS.networkInterfaces(),
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
}).pipe(Effect.orDie),
});
});
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
@@ -7,21 +7,18 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
DesktopEnvironment,
layer as makeDesktopEnvironmentLayer,
} from "../app/DesktopEnvironment.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const encoder = new TextEncoder();
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
en0: [
{
address: "192.168.1.20",
@@ -31,7 +28,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces = {
],
};
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
tailscale0: [
{
address: "100.90.1.2",
@@ -64,8 +61,15 @@ function mockSpawnerLayer(statusJson = "{}") {
);
}
function dieOnSpawnLayer() {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
);
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return makeDesktopEnvironmentLayer({
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
@@ -84,20 +88,22 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
});
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -105,24 +111,36 @@ function makeLayer(input: {
}
const withHarness = <A, E, R>(
networkInterfaces: DesktopNetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
effect: Effect.Effect<
A,
E,
| R
| DesktopEnvironment
| DesktopEnvironment.DesktopEnvironment
| FileSystem.FileSystem
| DesktopServerExposure.DesktopServerExposure
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-server-exposure-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
return yield* effect.pipe(
Effect.provide(
makeLayer({
baseDir,
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -222,6 +240,73 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("preserves persistence request context and the settings failure chain", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/desktop-settings.json",
cause: diskFailure,
});
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(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
assert.instanceOf(
modeError,
DesktopServerExposure.DesktopServerExposureModePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
assert.equal(modeError.mode, "network-accessible");
assert.strictEqual(modeError.cause, settingsFailure);
assert.strictEqual(modeError.cause.cause, diskFailure);
assert.equal(
modeError.message,
"Failed to persist desktop server exposure mode network-accessible.",
);
assert.notInclude(modeError.message, diskFailure.message);
const tailscaleError = yield* serverExposure
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
.pipe(Effect.flip);
assert.instanceOf(
tailscaleError,
DesktopServerExposure.DesktopTailscaleServePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
assert.equal(tailscaleError.enabled, true);
assert.equal(tailscaleError.port, 8443);
assert.strictEqual(tailscaleError.cause, settingsFailure);
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
assert.equal(
tailscaleError.message,
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
);
assert.notInclude(tailscaleError.message, diskFailure.message);
}),
{},
undefined,
settingsLayer,
);
});
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
withHarness(
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
@@ -239,6 +324,27 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
// mode stays at default "local-only", tailscaleServeEnabled stays false.
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
// would have crashed the test if the gate was missing.
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/"],
);
}),
{},
dieOnSpawnLayer(),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
+108 -93
View File
@@ -1,46 +1,35 @@
import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
DesktopServerExposureState,
import {
DesktopServerExposureModeSchema,
type AdvertisedEndpoint,
type AdvertisedEndpointProvider,
type DesktopServerExposureMode,
type DesktopServerExposureState,
} from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as 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 Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
readonly family: string | number;
readonly internal: boolean;
readonly netmask?: string;
readonly mac?: string;
readonly cidr?: string | null;
readonly scopeid?: number;
}
export type DesktopNetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
interface ResolvedDesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
@@ -87,7 +76,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
};
const resolveLanAdvertisedHost = (
networkInterfaces: DesktopNetworkInterfaces,
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
explicitHost: string | undefined,
): string | null => {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
@@ -112,7 +101,7 @@ const resolveLanAdvertisedHost = (
const resolveDesktopServerExposure = (input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly advertisedHostOverride?: string;
}): ResolvedDesktopServerExposure => {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
@@ -214,34 +203,56 @@ const resolveDesktopCoreAdvertisedEndpoints = (
return endpoints;
};
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
"DesktopServerExposureNoNetworkAddressError",
)<{
readonly port: number;
}> {
override get message() {
{
port: Schema.Number,
},
) {
override get message(): string {
return `No reachable network address is available for desktop network access on port ${this.port}.`;
}
}
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
"DesktopServerExposurePersistenceError",
)<{
readonly operation: DesktopServerExposurePersistenceOperation;
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
}> {
override get message() {
return `Failed to persist desktop ${this.operation} settings.`;
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
"DesktopServerExposureModePersistenceError",
{
mode: DesktopServerExposureModeSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop server exposure mode ${this.mode}.`;
}
}
export type DesktopServerExposureSetModeError =
| DesktopServerExposureNoNetworkAddressError
| DesktopServerExposurePersistenceError;
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
"DesktopTailscaleServePersistenceError",
{
enabled: Schema.Boolean,
port: Schema.NullOr(Schema.Number),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
}
}
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
export const DesktopServerExposureSetModeError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
]);
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
export const DesktopServerExposureError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
DesktopTailscaleServePersistenceError,
]);
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
export interface DesktopServerExposureBackendConfig {
readonly port: number;
@@ -256,36 +267,25 @@ export interface DesktopServerExposureChange {
readonly requiresRelaunch: boolean;
}
export interface DesktopServerExposureShape {
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
DesktopServerExposureShape
{
readonly getState: Effect.Effect<DesktopServerExposureState>;
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
readonly configureFromSettings: (input: {
readonly port: number;
}) => Effect.Effect<DesktopServerExposureState>;
readonly setMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
}
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
readonly mode: DesktopServerExposureMode;
@@ -307,10 +307,10 @@ interface ResolvedRuntimeState {
const initialRuntimeState = (): RuntimeState =>
runtimeStateFromResolvedExposure({
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DEFAULT_DESKTOP_SETTINGS,
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
exposure: resolveDesktopServerExposure({
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
port: 0,
networkInterfaces: {},
}),
@@ -344,7 +344,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
function runtimeStateFromResolvedExposure(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopSettings;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly exposure: ResolvedDesktopServerExposure;
readonly port: number;
}): RuntimeState {
@@ -365,9 +365,9 @@ function runtimeStateFromResolvedExposure(input: {
function resolveRuntimeState(input: {
readonly requestedMode: DesktopServerExposureMode;
readonly settings: DesktopSettings;
readonly settings: DesktopAppSettings.DesktopSettings;
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
readonly advertisedHostOverride: Option.Option<string>;
}): ResolvedRuntimeState {
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
@@ -404,14 +404,26 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
previous.bindHost !== next.bindHost ||
previous.localHttpUrl !== next.localHttpUrl;
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const networkInterfaces = yield* DesktopNetworkInterfacesService;
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
// spawn re-triggers the "Other apps" TCC prompt.
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
TAILSCALE_STATUS_CACHE_TTL,
);
const readNetworkInterfaces = networkInterfaces.read;
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
@@ -460,8 +472,8 @@ const make = Effect.gen(function* () {
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "server-exposure-mode",
new DesktopServerExposureModePersistenceError({
mode,
cause,
}),
),
@@ -488,8 +500,9 @@ const make = Effect.gen(function* () {
.pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposurePersistenceError({
operation: "tailscale-serve",
new DesktopTailscaleServePersistenceError({
enabled: input.enabled,
port: input.port ?? null,
cause,
}),
),
@@ -516,11 +529,20 @@ const make = Effect.gen(function* () {
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
// Don't spawn the Tailscale CLI when the user hasn't opted into any
// network exposure. The spawn itself triggers a macOS "Other apps"
// TCC prompt on Mac App Store Tailscale builds.
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
return coreEndpoints;
}
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
readMagicDnsName: cachedReadMagicDnsName,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -539,10 +561,3 @@ const make = Effect.gen(function* () {
});
export const layer = Layer.effect(DesktopServerExposure, make);
export const networkInterfacesLayer = Layer.succeed(
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesService.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
}),
);
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
Effect.gen(function* () {
let readerCalls = 0;
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
readMagicDnsName: Effect.sync(() => {
readerCalls += 1;
return "desktop.tail.ts.net";
}),
});
assert.equal(readerCalls, 1);
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["https://desktop.tail.ts.net/"],
);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
@@ -9,10 +9,10 @@ import {
} from "@t3tools/tailscale";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly networkInterfaces: NetworkInterfaces;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
@@ -103,8 +103,13 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly networkInterfaces: NetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
never,
ChildProcessSpawner.ChildProcessSpawner
>;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<
readonly AdvertisedEndpoint[],
@@ -112,12 +117,15 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const readDnsName =
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
)
? yield* readDnsName
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.orElseSucceed(() => null),
@@ -100,6 +100,44 @@ describe("ElectronApp", () => {
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("reports which app metadata property failed", () =>
Effect.gen(function* () {
const cause = new Error("version unavailable");
getVersionMock.mockImplementationOnce(() => {
throw cause;
});
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.metadata.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
assert.strictEqual(error.property, "app-version");
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
'Failed to read Electron app metadata property "app-version".',
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("preserves Electron readiness failures", () =>
Effect.gen(function* () {
const cause = new Error("ready failed");
whenReadyMock.mockRejectedValueOnce(cause);
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.whenReady.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
assert.strictEqual(error.isPackaged, true);
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
"Failed to wait for the Electron app to become ready (packaged: true).",
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes app event listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
+91 -42
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 Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
@@ -13,41 +14,64 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean;
}
export interface ElectronAppShape {
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
"ElectronAppMetadataReadError",
{
property: Schema.Literals(["app-version", "app-path"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Electron app metadata property "${this.property}".`;
}
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"@t3tools/desktop/electron/ElectronApp",
) {}
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
"ElectronAppWhenReadyError",
{
isPackaged: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
}
}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
readonly setPath: (
name: Parameters<Electron.App["setPath"]>[0],
path: string,
) => Effect.Effect<void>;
readonly setName: (name: string) => Effect.Effect<void>;
readonly setAboutPanelOptions: (
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
path?: string,
args?: readonly string[],
) => Effect.Effect<boolean>;
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronApp") {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
eventName: string,
@@ -63,16 +87,41 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
}),
).pipe(Effect.asVoid);
const make = ElectronApp.of({
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
})),
export const make = ElectronApp.of({
metadata: Effect.gen(function* () {
const appVersion = yield* Effect.try({
try: () => Electron.app.getVersion(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-version",
cause,
}),
});
const appPath = yield* Effect.try({
try: () => Electron.app.getAppPath(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-path",
cause,
}),
});
return {
appVersion,
appPath,
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
};
}),
name: Effect.sync(() => Electron.app.name),
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
whenReady: Effect.gen(function* () {
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
try: () => Electron.app.whenReady(),
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
});
}),
quit: Effect.sync(() => {
Electron.app.quit();
}),
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
@@ -90,4 +91,116 @@ describe("ElectronDialog", () => {
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
const owner = { id: 7 } as BrowserWindow;
showOpenDialogMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.pickFolder({
owner: Option.some(owner),
defaultPath: Option.some("/workspace"),
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
assert.isTrue(ElectronDialog.isElectronDialogError(error));
assert.strictEqual(error.ownerWindowId, 7);
assert.strictEqual(error.defaultPath, "/workspace");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 7");
assert.include(error.message, "/workspace");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.showMessageBox({
type: "warning",
title: "Unsaved changes",
message: "Discard changes?",
detail: "This cannot be undone.",
buttons: ["Cancel", "Discard"],
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
assert.strictEqual(error.type, "warning");
assert.strictEqual(error.titleLength, "Unsaved changes".length);
assert.strictEqual(error.messageLength, "Discard changes?".length);
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
assert.strictEqual(error.buttonCount, 2);
assert.notProperty(error, "title");
assert.notProperty(error, "dialogMessage");
assert.notProperty(error, "dialogDetail");
assert.notProperty(error, "buttons");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "warning");
assert.notInclude(error.message, "Unsaved changes");
assert.notInclude(error.message, "Discard changes?");
assert.notInclude(error.message, "This cannot be undone.");
assert.notInclude(error.message, "Cancel");
assert.notInclude(error.message, "Discard");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves error box request context and cause in the defect", () =>
Effect.gen(function* () {
const cause = new Error("error box failed");
showErrorBoxMock.mockImplementation(() => {
throw cause;
});
const dialog = yield* ElectronDialog.ElectronDialog;
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
assert.strictEqual(error.titleLength, "Startup failed".length);
assert.strictEqual(error.contentLength, "Could not start.".length);
assert.notProperty(error, "title");
assert.notProperty(error, "content");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "Startup failed");
assert.notInclude(error.message, "Could not start.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
});
+140 -26
View File
@@ -2,11 +2,80 @@ 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 CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
"ElectronDialogShowMessageBoxError",
{
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
titleLength: Schema.NullOr(Schema.Number),
messageLength: Schema.Number,
detailLength: Schema.NullOr(Schema.Number),
buttonCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const type = this.type === null ? "untyped" : this.type;
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
}
}
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
"ElectronDialogShowErrorBoxError",
{
titleLength: Schema.Number,
contentLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
}
}
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
export type ElectronDialogError = typeof ElectronDialogError.Type;
export const isElectronDialogError = Schema.is(ElectronDialogError);
export interface ElectronDialogPickFolderInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
@@ -17,23 +86,29 @@ export interface ElectronDialogConfirmInput {
readonly message: string;
}
export interface ElectronDialogShape {
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
export class ElectronDialog extends Context.Service<
ElectronDialog,
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"@t3tools/desktop/electron/ElectronDialog",
) {}
const make = ElectronDialog.of({
export const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
properties: ["openDirectory", "createDirectory"],
@@ -43,10 +118,18 @@ const make = ElectronDialog.of({
defaultPath,
}),
});
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
onSome: (owner) =>
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogPickFolderError({
ownerWindowId,
defaultPath,
cause,
}),
});
if (result.canceled) {
@@ -68,17 +151,48 @@ const make = ElectronDialog.of({
noLink: true,
message: normalizedMessage,
};
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
ownerWindowId,
promptLength: normalizedMessage.length,
cause,
}),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
showErrorBox: (title, content) =>
Effect.sync(() => {
Electron.dialog.showErrorBox(title, content);
showMessageBox: (options) =>
Effect.tryPromise({
try: () => Electron.dialog.showMessageBox(options),
catch: (cause) =>
new ElectronDialogShowMessageBoxError({
type: options.type ?? null,
titleLength: options.title?.length ?? null,
messageLength: options.message.length,
detailLength: options.detail?.length ?? null,
buttonCount: options.buttons?.length ?? 0,
cause,
}),
}),
showErrorBox: (title, content) =>
Effect.try({
try: () => Electron.dialog.showErrorBox(title, content),
catch: (cause) =>
new ElectronDialogShowErrorBoxError({
titleLength: title.length,
contentLength: content.length,
cause,
}),
}).pipe(Effect.orDie),
});
export const layer = Layer.succeed(ElectronDialog, make);
+106 -6
View File
@@ -1,5 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
@@ -24,6 +27,16 @@ vi.mock("electron", () => ({
import * as ElectronMenu from "./ElectronMenu.ts";
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();
@@ -42,7 +55,7 @@ describe("ElectronMenu", () => {
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("resolves with the clicked leaf item id", () =>
@@ -63,37 +76,41 @@ 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(),
});
assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
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,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
@@ -114,6 +131,89 @@ describe("ElectronMenu", () => {
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1);
}).pipe(Effect.provide(ElectronMenu.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves application-menu failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("application menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "set-application-menu");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 2);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
buildFromTemplateMock.mockReturnValueOnce({
popup: () => {
throw cause;
},
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.popupTemplate({
window: { id: 41 } as Electron.BrowserWindow,
template: [{ label: "Copy" }],
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "popup-template");
assert.equal(error.windowId, 41);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves context-menu failures with normalized item context", () =>
Effect.gen(function* () {
const cause = new Error("context menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.showContextMenu({
window: { id: 42 } as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "show-context-menu");
assert.equal(error.windowId, 42);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
});
+120 -39
View File
@@ -1,8 +1,10 @@
import type { ContextMenuItem } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
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";
@@ -22,19 +24,40 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
export interface ElectronMenuShape {
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
const ElectronMenuOperation = Schema.Literals([
"set-application-menu",
"popup-template",
"show-context-menu",
]);
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
"ElectronMenuOperationError",
{
operation: ElectronMenuOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
itemCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
}
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
) {}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronMenu") {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
@@ -44,6 +67,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
@@ -65,19 +94,27 @@ 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 layer = Layer.sync(ElectronMenu, () => {
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
if (process.platform !== "darwin") {
if (platform !== "darwin") {
return Option.none();
}
if (destructiveMenuIconCache !== undefined) {
@@ -89,6 +126,7 @@ export const layer = Layer.sync(ElectronMenu, () => {
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
@@ -134,16 +172,36 @@ export const layer = Layer.sync(ElectronMenu, () => {
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
Effect.try({
try: () => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
},
catch: (cause) =>
new ElectronMenuOperationError({
operation: "set-application-menu",
platform,
windowId: null,
itemCount: template.length,
cause,
}),
}).pipe(Effect.orDie),
popupTemplate: (input) =>
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
input.template.length === 0
? Effect.void
: Effect.try({
try: () =>
Electron.Menu.buildFromTemplate([...input.template]).popup({
window: input.window,
}),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "popup-template",
platform,
windowId: input.window.id,
itemCount: input.template.length,
cause,
}),
}).pipe(Effect.orDie),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
@@ -161,21 +219,44 @@ export const layer = Layer.sync(ElectronMenu, () => {
resume(Effect.succeed(selectedItemId));
};
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(
input.position,
input.window.webContents.getZoomFactor(),
);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
} catch (cause) {
if (completed) {
return;
}
completed = true;
resume(
Effect.die(
new ElectronMenuOperationError({
operation: "show-context-menu",
platform,
windowId: input.window.id,
itemCount: normalizedItems.length,
cause,
}),
),
);
}
}),
});
});
export const layer = Layer.effect(ElectronMenu, make);
@@ -1,105 +1,229 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
registerFileProtocolMock: vi.fn(),
registerSchemesAsPrivilegedMock: vi.fn(),
unregisterProtocolMock: vi.fn(),
}));
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
netFetchMock: vi.fn(),
unhandleMock: vi.fn(),
}));
vi.mock("electron", () => ({
protocol: {
registerFileProtocol: registerFileProtocolMock,
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
unregisterProtocol: unregisterProtocolMock,
},
net: { fetch: netFetchMock },
protocol: { handle: handleMock, unhandle: unhandleMock },
}));
import * as ElectronProtocol from "./ElectronProtocol.ts";
describe("ElectronProtocol", () => {
beforeEach(() => {
registerFileProtocolMock.mockReset();
registerSchemesAsPrivilegedMock.mockReset();
unregisterProtocolMock.mockReset();
handleMock.mockReset();
netFetchMock.mockReset();
unhandleMock.mockReset();
});
it("normalizes safe desktop protocol pathnames", () => {
assert.equal(
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
"settings/general",
);
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
});
it.effect("proxies the stable renderer origin to the current app server", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock.mockResolvedValue(new Response("ok"));
it.effect("registers desktop scheme privileges through a layer", () =>
Effect.scoped(
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
Effect.andThen(
Effect.sync(() => {
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
[
[
{
scheme: "t3",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
],
],
]);
}),
),
),
),
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:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
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(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"img-src 'self' t3code-dev: blob: data: http: https:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"font-src 'self' t3code-dev: data:",
);
}),
);
assert.deepEqual(
handleMock.mock.calls.map((call) => call[0]),
["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)),
);
it.effect("scopes registered file protocols", () =>
it.effect("rejects custom protocol requests for another host", () =>
Effect.gen(function* () {
let capturedHandler:
| ((
request: Electron.ProtocolRequest,
callback: (response: Electron.ProtocolResponse) => void,
) => void)
| undefined;
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
capturedHandler = handler;
return true;
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
const response = yield* Effect.scoped(
Effect.gen(function* () {
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
yield* electronProtocol.registerFileProtocol({
scheme: "t3",
handler: () => Effect.succeed({ path: "/app/index.html" }),
});
assert.isDefined(capturedHandler);
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
resume(Effect.succeed(response)),
);
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
}),
);
assert.deepEqual(response, { path: "/app/index.html" });
assert.deepEqual(
registerFileProtocolMock.mock.calls.map((call) => call[0]),
["t3"],
);
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
assert.equal(response.status, 404);
assert.equal(netFetchMock.mock.calls.length, 0);
}).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");
handleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const error = yield* Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: undefined,
}),
).pipe(Effect.flip);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
assert.equal(error.scheme, "t3code-dev");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol unregistration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol unregistration failed");
unhandleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const exit = yield* Effect.exit(
Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
}),
),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
assert.equal(error.scheme, "t3code");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
}
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: "clerk.t3.codes",
});
const directives = Object.fromEntries(
policy.split("; ").map((directive) => {
const [name, ...sources] = directive.split(" ");
return [name, sources];
}),
);
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
"blob:",
"data:",
"http:",
"https:",
]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
+174 -240
View File
@@ -1,272 +1,206 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
export const DESKTOP_HOST = "app";
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
export const DESKTOP_SCHEME = "t3";
export function getDesktopScheme(isDevelopment: boolean): string {
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
}
export class ElectronProtocolRegistrationError extends Data.TaggedError(
export function getDesktopOrigin(isDevelopment: boolean): string {
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
}
export function getDesktopUrl(isDevelopment: boolean): string {
return `${getDesktopOrigin(isDevelopment)}/`;
}
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
"ElectronProtocolRegistrationError",
)<{
readonly scheme: string;
readonly cause: unknown;
}> {
override get message() {
return `Failed to register ${this.scheme}: file protocol.`;
}
}
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
"ElectronProtocolStaticBundleMissingError",
)<{}> {
override get message() {
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
}
}
export interface ElectronProtocolShape {
readonly registerFileProtocol: <E, R>(input: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
readonly registerDesktopFileProtocol: Effect.Effect<
void,
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
>;
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
const segments: string[] = [];
for (const segment of rawPath.split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
return Option.none();
}
segments.push(segment);
}
return Option.some(segments.join("/"));
}
const registerDesktopSchemePrivileges = Effect.sync(() => {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
const resolveDesktopStaticDir: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment
> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidates = [
environment.path.join(environment.appRoot, "apps/server/dist/client"),
environment.path.join(environment.appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
const hasIndex = yield* fileSystem
.exists(environment.path.join(candidate, "index.html"))
.pipe(Effect.orElseSucceed(() => false));
if (hasIndex) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
function* (
staticRoot: string,
requestUrl: string,
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
if (Option.isNone(normalizedPath)) {
return environment.path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
const resolvedPath = environment.path.join(staticRoot, requestedPath);
if (environment.path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = environment.path.join(resolvedPath, "index.html");
const nestedIndexExists = yield* fileSystem
.exists(nestedIndex)
.pipe(Effect.orElseSucceed(() => false));
if (nestedIndexExists) {
return nestedIndex;
}
return environment.path.join(staticRoot, "index.html");
{
scheme: Schema.String,
cause: Schema.Defect(),
},
);
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
try {
const url = new URL(requestUrl);
return environment.path.extname(url.pathname).length > 0;
} catch {
return false;
) {
override get message(): string {
return `Failed to register Electron protocol scheme "${this.scheme}".`;
}
}
const make = Effect.gen(function* () {
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
"ElectronProtocolUnregistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
}
}
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
function* <E, R>({
scheme,
handler,
onFailure,
}: {
readonly scheme: string;
readonly handler: (
request: Electron.ProtocolRequest,
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
readonly onFailure?: (
request: Electron.ProtocolRequest,
cause: Cause.Cause<E>,
) => Electron.ProtocolResponse;
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
yield* Effect.annotateCurrentSpan({ scheme });
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
Effect.map((protocols) => protocols.has(scheme)),
);
if (alreadyRegistered) {
return;
}
export interface DesktopProtocolRegistrationInput {
readonly scheme: string;
readonly targetOrigin: URL;
readonly backendOrigin: URL;
readonly clerkFrontendApiHostname: string | undefined;
}
const context = yield* Effect.context<R>();
const runPromise = Effect.runPromiseWith(context);
export class ElectronProtocol extends Context.Service<
ElectronProtocol,
{
readonly registerDesktopProtocol: (
input: DesktopProtocolRegistrationInput,
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronProtocol") {}
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
const clerkOrigin = input.clerkFrontendApiHostname
? `https://${input.clerkFrontendApiHostname}`
: undefined;
const scriptSources = [
"'self'",
"'unsafe-inline'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
// The renderer connects directly to user-configured environments in addition to
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
"frame-src 'self' https://challenges.cloudflare.com",
"form-action 'self'",
].join("; ");
}
function withContentSecurityPolicy(response: Response, policy: string): Response {
const headers = new Headers(response.headers);
headers.set("Content-Security-Policy", policy);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
async function proxyRequest(
request: Request,
targetOrigin: URL,
contentSecurityPolicy: string,
): Promise<Response> {
const requestUrl = new URL(request.url);
if (requestUrl.host !== DESKTOP_HOST) {
return new Response(null, { status: 404 });
}
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,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
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);
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
function* (input: DesktopProtocolRegistrationInput) {
if (yield* Ref.get(registered)) return;
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
const registered = Electron.protocol.registerFileProtocol(
scheme,
(request, callback) => {
const response = handler(request).pipe(
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
Effect.catchCause((cause) =>
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
),
);
void runPromise(response).then(callback, () => callback({ error: -2 }));
},
Electron.protocol.handle(input.scheme, (request) =>
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
);
if (!registered) {
throw new ElectronProtocolRegistrationError({
scheme,
cause: "registerFileProtocol returned false",
});
}
},
catch: (cause) =>
cause instanceof ElectronProtocolRegistrationError
? cause
: new ElectronProtocolRegistrationError({ scheme, cause }),
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
),
),
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
() =>
Effect.sync(() => {
Electron.protocol.unregisterProtocol(scheme);
}).pipe(
Effect.andThen(
Ref.update(registeredProtocols, (protocols) => {
const next = new Set(protocols);
next.delete(scheme);
return next;
Effect.try({
try: () => Electron.protocol.unhandle(input.scheme),
catch: (cause) =>
new ElectronProtocolUnregistrationError({
scheme: input.scheme,
cause,
}),
),
),
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
);
},
);
const registerDesktopFileProtocol = Effect.gen(function* () {
const environment = yield* DesktopEnvironment;
if (environment.isDevelopment) return;
const staticRoot = yield* resolveDesktopStaticDir;
if (Option.isNone(staticRoot)) {
return yield* new ElectronProtocolStaticBundleMissingError();
}
const staticRootResolved = environment.path.resolve(staticRoot.value);
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
yield* registerFileProtocol({
scheme: DESKTOP_SCHEME,
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment;
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = environment.path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url, environment);
const exists = yield* fileSystem
.exists(resolvedCandidate)
.pipe(Effect.orElseSucceed(() => false));
if (!isInRoot || !exists) {
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
}
return { path: resolvedCandidate } as const;
}),
onFailure: () => ({ path: fallbackIndex }),
});
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
return ElectronProtocol.of({
registerFileProtocol,
registerDesktopFileProtocol,
});
return ElectronProtocol.of({ registerDesktopProtocol });
});
export const layer = Layer.effect(ElectronProtocol, make);
@@ -1,56 +1,69 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
};
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
"ElectronSafeStorageAvailabilityError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to check encryption availability.";
}
}
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
"ElectronSafeStorageEncryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to encrypt a string.";
}
}
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
"ElectronSafeStorageDecryptError",
)<{
readonly cause: unknown;
}> {
override get message() {
{
...electronSafeStorageErrorFields,
},
) {
override get message(): string {
return "Electron safe storage failed to decrypt a string.";
}
}
export interface ElectronSafeStorageShape {
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
export const ElectronSafeStorageError = Schema.Union([
ElectronSafeStorageAvailabilityError,
ElectronSafeStorageEncryptError,
ElectronSafeStorageDecryptError,
]);
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
ElectronSafeStorageShape
{
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
readonly encryptString: (
value: string,
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
const make = ElectronSafeStorage.of({
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
+8 -9
View File
@@ -20,16 +20,15 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
export interface ElectronShellShape {
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
) {}
const make = ElectronShell.of({
export const make = ElectronShell.of({
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
@@ -8,6 +8,7 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
themeState: {
shouldUseDarkColors: true,
themeSource: "system",
setSourceError: null as unknown,
},
}));
@@ -17,6 +18,9 @@ vi.mock("electron", () => ({
return themeState.shouldUseDarkColors;
},
set themeSource(value: string) {
if (themeState.setSourceError !== null) {
throw themeState.setSourceError;
}
themeState.themeSource = value;
},
on: onMock,
@@ -32,6 +36,7 @@ describe("ElectronTheme", () => {
removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true;
themeState.themeSource = "system";
themeState.setSourceError = null;
});
it.effect("scopes native theme update listeners", () =>
@@ -49,4 +54,21 @@ describe("ElectronTheme", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
it.effect("preserves the requested source and cause when setting the theme fails", () =>
Effect.gen(function* () {
const cause = new Error("theme source failed");
themeState.setSourceError = cause;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const error = yield* Effect.flip(electronTheme.setSource("dark"));
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
assert.strictEqual(error.source, "dark");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "dark");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
});
+28 -12
View File
@@ -1,27 +1,43 @@
import type { DesktopTheme } from "@t3tools/contracts";
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export interface ElectronThemeShape {
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
"ElectronThemeSetSourceError",
{
source: DesktopThemeSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to set the Electron theme source to ${this.source}.`;
}
}
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
) {}
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
const make = ElectronTheme.of({
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.suspend(() => {
Electron.nativeTheme.themeSource = theme;
return Effect.void;
Effect.try({
try: () => {
Electron.nativeTheme.themeSource = theme;
},
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
}),
onUpdated: (listener) =>
Effect.acquireRelease(
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
@@ -11,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(),
@@ -34,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();
@@ -65,15 +66,77 @@ describe("ElectronUpdater", () => {
const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "beta";
const exit = yield* Effect.exit(updater.checkForUpdates);
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
}
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "beta");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves the execution-time channel on download failures", () =>
Effect.gen(function* () {
const cause = new Error("download unavailable");
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "nightly";
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to download the update on channel nightly.",
);
assert.notInclude(error.message, cause.message);
}).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");
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
throw cause;
});
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "alpha";
const error = yield* updater
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "alpha");
assert.equal(error.isSilent, true);
assert.equal(error.isForceRunAfter, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
);
assert.notInclude(error.message, cause.message);
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
+93 -60
View File
@@ -1,7 +1,7 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { autoUpdater } from "electron-updater";
@@ -10,67 +10,78 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
"ElectronUpdaterCheckForUpdatesError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to check for updates.";
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
}
}
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
"ElectronUpdaterDownloadUpdateError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to download the update.";
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
}
}
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
"ElectronUpdaterQuitAndInstallError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Electron updater failed to quit and install the update.";
{
channel: Schema.NullOr(Schema.String),
isSilent: Schema.Boolean,
isForceRunAfter: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
}
}
export type ElectronUpdaterError =
| ElectronUpdaterCheckForUpdatesError
| ElectronUpdaterDownloadUpdateError
| ElectronUpdaterQuitAndInstallError;
export const ElectronUpdaterError = Schema.Union([
ElectronUpdaterCheckForUpdatesError,
ElectronUpdaterDownloadUpdateError,
ElectronUpdaterQuitAndInstallError,
]);
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
export interface ElectronUpdaterShape {
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronUpdater extends Context.Service<
ElectronUpdater,
{
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
readonly setChannel: (channel: string) => Effect.Effect<void>;
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
readonly allowDowngrade: Effect.Effect<boolean>;
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly 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>;
readonly quitAndInstall: (options: {
readonly isSilent: boolean;
readonly isForceRunAfter: boolean;
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
export const make = ElectronUpdater.of({
setFeedURL: (options) =>
Effect.suspend(() => {
autoUpdater.setFeedURL(options);
@@ -102,23 +113,43 @@ export const layer = Layer.succeed(ElectronUpdater, {
autoUpdater.allowDowngrade = value;
return Effect.void;
}),
setFullChangelog: (value) =>
Effect.suspend(() => {
autoUpdater.fullChangelog = value;
return Effect.void;
}),
setDisableDifferentialDownload: (value) =>
Effect.suspend(() => {
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
checkForUpdates: Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
}).pipe(Effect.asVoid),
downloadUpdate: Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
}).pipe(Effect.asVoid),
checkForUpdates: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
downloadUpdate: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) =>
new ElectronUpdaterQuitAndInstallError({
channel,
isSilent,
isForceRunAfter,
cause,
}),
});
}),
on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as {
@@ -136,4 +167,6 @@ export const layer = Layer.succeed(ElectronUpdater, {
}),
).pipe(Effect.asVoid);
},
} satisfies ElectronUpdaterShape);
});
export const layer = Layer.succeed(ElectronUpdater, make);
+194 -10
View File
@@ -1,26 +1,39 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
getAllWindowsMock: vi.fn(),
}));
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
() => ({
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
focus: appFocusMock,
},
BrowserWindow: {
BrowserWindow: Object.assign(browserWindowMock, {
getAllWindows: getAllWindowsMock,
},
getFocusedWindow: getFocusedWindowMock,
}),
}));
import * as ElectronWindow from "./ElectronWindow.ts";
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
const TestLayer = ElectronWindow.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
return {
id: input.id,
isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow;
}
@@ -28,13 +41,78 @@ function makeBrowserWindow(input: { readonly destroyed: boolean }) {
describe("ElectronWindow", () => {
beforeEach(() => {
appFocusMock.mockReset();
browserWindowMock.mockReset();
getAllWindowsMock.mockReset();
getFocusedWindowMock.mockReset();
});
it.effect("preserves schema-safe creation context and the Electron cause", () =>
Effect.gen(function* () {
const cause = new Error("native BrowserWindow construction failed");
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
throw cause;
});
const options = {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
icon: {} as Electron.NativeImage,
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
spellcheck: true,
},
} satisfies Electron.BrowserWindowConstructorOptions;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const error = yield* electronWindow.create(options).pipe(Effect.flip);
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
assert.deepEqual(error.options, {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
},
});
assert.isFalse("icon" in error.options);
assert.isFalse("spellcheck" in error.options.webPreferences);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
assert.notInclude(error.message, cause.message);
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("skips windows destroyed before appearance sync runs", () =>
Effect.gen(function* () {
const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ destroyed: true });
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = [];
@@ -46,6 +124,112 @@ describe("ElectronWindow", () => {
);
assert.deepEqual(syncedWindows, [liveWindow]);
}).pipe(Effect.provide(ElectronWindow.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves window enumeration failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("window enumeration failed");
getAllWindowsMock.mockImplementationOnce(() => {
throw cause;
});
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "list-windows");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves reveal failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window restore failed");
const window = {
id: 41,
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => true),
restore: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.reveal(window));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "reveal-window");
assert.equal(error.windowId, 41);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves message delivery failures with window and channel context", () =>
Effect.gen(function* () {
const cause = new Error("renderer send failed");
const window = {
id: 42,
isDestroyed: vi.fn(() => false),
webContents: {
send: vi.fn(() => {
throw cause;
}),
},
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "send-window-message");
assert.equal(error.windowId, 42);
assert.equal(error.channel, "desktop:update");
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves destroy failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window destroy failed");
const window = {
id: 43,
destroy: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.destroyAll);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "destroy-window");
assert.equal(error.windowId, 43);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
});
+223 -72
View File
@@ -1,47 +1,135 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to create Electron BrowserWindow.";
const ElectronWindowCreateOptions = Schema.Struct({
title: Schema.NullOr(Schema.String),
width: Schema.NullOr(Schema.Number),
height: Schema.NullOr(Schema.Number),
minWidth: Schema.NullOr(Schema.Number),
minHeight: Schema.NullOr(Schema.Number),
show: Schema.NullOr(Schema.Boolean),
modal: Schema.NullOr(Schema.Boolean),
frame: Schema.NullOr(Schema.Boolean),
transparent: Schema.NullOr(Schema.Boolean),
backgroundColor: Schema.NullOr(Schema.String),
webPreferences: Schema.Struct({
preload: Schema.NullOr(Schema.String),
partition: Schema.NullOr(Schema.String),
sandbox: Schema.NullOr(Schema.Boolean),
contextIsolation: Schema.NullOr(Schema.Boolean),
nodeIntegration: Schema.NullOr(Schema.Boolean),
webviewTag: Schema.NullOr(Schema.Boolean),
}),
});
const ElectronWindowOperation = Schema.Literals([
"list-windows",
"get-focused-window",
"inspect-window",
"reveal-window",
"send-window-message",
"destroy-window",
]);
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
options: ElectronWindowCreateOptions,
cause: Schema.Defect(),
},
) {
override get message(): string {
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
const dimensions =
this.options.width === null || this.options.height === null
? ""
: ` (${this.options.width}x${this.options.height})`;
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
}
}
export interface ElectronWindowShape {
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
"ElectronWindowOperationError",
{
operation: ElectronWindowOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
}
}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
) {}
export class ElectronWindow extends Context.Service<
ElectronWindow,
{
readonly create: (
options: Electron.BrowserWindowConstructorOptions,
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
readonly syncAllAppearance: <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) => Effect.Effect<void, E, R>;
}
>()("@t3tools/desktop/electron/ElectronWindow") {}
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const liveMain = Ref.get(mainWindowRef).pipe(
Effect.map(Option.filter((value) => !value.isDestroyed())),
);
const listWindows = Effect.try({
try: () => Electron.BrowserWindow.getAllWindows(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "list-windows",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
Effect.try({
try: () => window.isDestroyed(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "inspect-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const liveMain = Effect.gen(function* () {
const main = yield* Ref.get(mainWindowRef);
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
return Option.none<Electron.BrowserWindow>();
}
return main;
});
const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain;
@@ -49,27 +137,60 @@ const make = Effect.gen(function* () {
return main;
}
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
);
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
return Option.none<Electron.BrowserWindow>();
}
return first;
});
const focusedMainOrFirst = Effect.sync(() =>
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
),
).pipe(
Effect.flatMap((focused) =>
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
),
);
const focusedMainOrFirst = Effect.gen(function* () {
const focused = yield* Effect.try({
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "get-focused-window",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
return focused;
}
return yield* currentMainOrFirst;
});
return ElectronWindow.of({
create: (options) =>
Effect.try({
create: (options) => {
const webPreferences = options.webPreferences;
const diagnosticOptions = {
title: options.title ?? null,
width: options.width ?? null,
height: options.height ?? null,
minWidth: options.minWidth ?? null,
minHeight: options.minHeight ?? null,
show: options.show ?? null,
modal: options.modal ?? null,
frame: options.frame ?? null,
transparent: options.transparent ?? null,
backgroundColor: options.backgroundColor ?? null,
webPreferences: {
preload: webPreferences?.preload ?? null,
partition: webPreferences?.partition ?? null,
sandbox: webPreferences?.sandbox ?? null,
contextIsolation: webPreferences?.contextIsolation ?? null,
nodeIntegration: webPreferences?.nodeIntegration ?? null,
webviewTag: webPreferences?.webviewTag ?? null,
},
} satisfies typeof ElectronWindowCreateOptions.Type;
return Effect.try({
try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ cause }),
}),
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
});
},
main: liveMain,
currentMainOrFirst,
focusedMainOrFirst,
@@ -85,45 +206,75 @@ const make = Effect.gen(function* () {
return Option.none();
}),
reveal: (window) =>
Effect.sync(() => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (process.platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
Effect.try({
try: () => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
},
catch: (cause) =>
new ElectronWindowOperationError({
operation: "reveal-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie),
sendAll: (channel, ...args) =>
Effect.gen(function* () {
for (const window of yield* listWindows) {
if (yield* isWindowDestroyed(window)) {
continue;
}
window.webContents.send(channel, ...args);
yield* Effect.try({
try: () => window.webContents.send(channel, ...args),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "send-window-message",
platform,
windowId: window.id,
channel,
cause,
}),
}).pipe(Effect.orDie);
}
}),
destroyAll: Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
window.destroy();
destroyAll: Effect.gen(function* () {
for (const window of yield* listWindows) {
yield* Effect.try({
try: () => window.destroy(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "destroy-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) {
const windows = Electron.BrowserWindow.getAllWindows();
const windows = yield* listWindows;
for (const window of windows) {
if (window.isDestroyed()) {
if (yield* isWindowDestroyed(window)) {
continue;
}
yield* sync(window);
+79
View File
@@ -0,0 +1,79 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
import * as DesktopIpc from "./DesktopIpc.ts";
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
channel: "desktop.test.invoke",
handler: () => Effect.void,
};
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
channel: "desktop.test.sync",
handler: () => Effect.void,
};
function makeIpcMain(
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
): DesktopIpc.DesktopIpcMain {
return {
removeHandler: vi.fn(),
handle: vi.fn(),
removeAllListeners: vi.fn(),
on: vi.fn(),
...overrides,
};
}
describe("DesktopIpc", () => {
it.effect("preserves invoke registration context and cause", () =>
Effect.gen(function* () {
const cause = new Error("invoke registration failed");
const ipcMain = makeIpcMain({
handle: () => {
throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "invoke");
assert.strictEqual(error.channel, invokeMethod.channel);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "invoke");
assert.include(error.message, invokeMethod.channel);
assert.notInclude(error.message, cause.message);
}),
);
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
Effect.gen(function* () {
const cause = new Error("sync unregistration failed");
let removeCount = 0;
const ipcMain = makeIpcMain({
removeAllListeners: () => {
removeCount += 1;
if (removeCount === 2) throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "sync");
assert.strictEqual(error.channel, syncMethod.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}),
);
});
+91 -35
View File
@@ -1,5 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -23,6 +24,39 @@ export interface DesktopIpcMain {
on(channel: string, listener: DesktopIpcSyncListener): void;
}
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
"DesktopIpcRegistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
"DesktopIpcUnregistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export const DesktopIpcError = Schema.Union([
DesktopIpcRegistrationError,
DesktopIpcUnregistrationError,
]);
export type DesktopIpcError = typeof DesktopIpcError.Type;
export const isDesktopIpcError = Schema.is(DesktopIpcError);
export interface DesktopIpcMethod<E, R> {
readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
@@ -33,20 +67,19 @@ export interface DesktopSyncIpcMethod<E, R> {
readonly handler: () => Effect.Effect<unknown, E, R>;
}
export interface DesktopIpcShape {
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export class DesktopIpc extends Context.Service<
DesktopIpc,
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
DesktopIpc.of({
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
channel,
@@ -57,18 +90,27 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
Effect.try({
try: () => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
}),
() => Effect.sync(() => ipcMain.removeHandler(channel)),
() =>
Effect.try({
try: () => ipcMain.removeHandler(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
}).pipe(Effect.orDie),
);
}),
@@ -81,22 +123,36 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease(
Effect.sync(() => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
);
});
Effect.try({
try: () => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(
Effect.annotateLogs({ channel }),
Effect.withSpan("desktop.ipc.invokeSync"),
),
);
});
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
}),
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
() =>
Effect.try({
try: () => ipcMain.removeAllListeners(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
}).pipe(Effect.orDie),
);
}),
});
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
/**
* Convenience helpers for creating IPC methods
*/
+26 -27
View File
@@ -1,21 +1,12 @@
import * as Effect from "effect/Effect";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
createCloudAuthRequest,
fetchCloudAuth,
getCloudAuthToken,
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -42,26 +33,31 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstrap,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
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.gen(function* () {
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);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
@@ -77,19 +73,22 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
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);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(createCloudAuthRequest);
yield* ipc.handle(getCloudAuthToken);
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
});
+47 -12
View File
@@ -3,13 +3,9 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
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";
@@ -17,14 +13,14 @@ 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";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
@@ -38,4 +34,43 @@ 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";
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
export const getClientSettings = makeIpcMethod({
export const getClientSettings = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(ClientSettingsSchema),
@@ -17,7 +17,7 @@ export const getClientSettings = makeIpcMethod({
}),
});
export const setClientSettings = makeIpcMethod({
export const setClientSettings = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
payload: ClientSettingsSchema,
result: Schema.Void,
@@ -1,105 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"x-mobile": "1",
},
body,
});
assert(forwardedRequest !== null);
assert.equal(
forwardedRequest.headers["content-type"],
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
-154
View File
@@ -1,154 +0,0 @@
import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
}> {
override get message() {
return this.reason;
}
}
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
});
}
return url;
}
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
result: Schema.String,
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
return yield* cloudAuth.createRequest;
}),
});
export const getCloudAuthToken = makeIpcMethod({
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return Option.getOrNull(yield* tokenStore.get);
}),
});
export const setCloudAuthToken = makeIpcMethod({
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
return yield* tokenStore.set(token);
}),
});
export const clearCloudAuthToken = makeIpcMethod({
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
yield* tokenStore.clear;
}),
});
export const fetchCloudAuth = makeIpcMethod({
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
payload: DesktopCloudAuthFetchInputSchema,
result: DesktopCloudAuthFetchResultSchema,
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
const url = yield* Effect.try({
try: () => validateClerkFrontendApiUrl(input.url),
catch: (cause) =>
cause instanceof DesktopCloudAuthFetchError
? cause
: new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch received an invalid URL.",
cause,
}),
});
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
}),
});
@@ -0,0 +1,37 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
@@ -0,0 +1,54 @@
import { it as effectIt } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as PreviewManager from "../../preview/Manager.ts";
import * as PreviewIpc from "./preview.ts";
const { fromPartition } = vi.hoisted(() => ({
fromPartition: vi.fn(() => {
throw new Error("Session can only be received when app is ready");
}),
}));
vi.mock("electron", () => ({
BrowserWindow: {
getAllWindows: vi.fn(() => []),
},
session: {
fromPartition,
},
webContents: {
fromId: vi.fn(() => null),
},
}));
describe("preview IPC methods", () => {
beforeEach(() => {
fromPartition.mockClear();
});
it("does not access the Electron session while the module loads", async () => {
await expect(import("./preview.ts")).resolves.toBeDefined();
expect(fromPartition).not.toHaveBeenCalled();
});
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
Effect.map(
PreviewIpc.registerWebview
.handler({ tabId: "tab-1", webContentsId: 0 })
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
(exit) => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Cause.findErrorOption(exit.cause);
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
expect(fromPartition).not.toHaveBeenCalled();
},
),
);
});
+370
View File
@@ -0,0 +1,370 @@
import {
DesktopPreviewAnnotationThemeInputSchema,
DesktopPreviewArtifactInputSchema,
DesktopPreviewAutomationClickInputSchema,
DesktopPreviewAutomationEvaluateInputSchema,
DesktopPreviewAutomationPressInputSchema,
DesktopPreviewAutomationScrollInputSchema,
DesktopPreviewAutomationTypeInputSchema,
DesktopPreviewAutomationWaitForInputSchema,
DesktopPreviewConfigInputSchema,
DesktopPreviewNavigateInputSchema,
DesktopPreviewRecordingArtifactSchema,
DesktopPreviewRecordingSaveInputSchema,
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) =>
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
);
yield* manager.subscribeRecordingFrames((frame) =>
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
);
yield* manager.subscribePointerEvents((event) =>
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
);
});
export const createTab = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.createTab(tabId);
}),
});
export const closeTab = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.closeTab(tabId);
}),
});
export const registerWebview = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
payload: DesktopPreviewRegisterWebviewInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.registerWebview(tabId, webContentsId);
}),
});
export const navigate = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
payload: DesktopPreviewNavigateInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.navigate(tabId, url);
}),
});
const tabMethod = (
channel: string,
name: string,
invoke: (
manager: PreviewManager.PreviewManager["Service"],
tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) =>
DesktopIpc.makeIpcMethod({
channel,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn(name)(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* invoke(manager, tabId);
}),
});
export const goBack = tabMethod(
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
"desktop.ipc.preview.goBack",
(manager, tabId) => manager.goBack(tabId),
);
export const goForward = tabMethod(
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
"desktop.ipc.preview.goForward",
(manager, tabId) => manager.goForward(tabId),
);
export const refresh = tabMethod(
IpcChannels.PREVIEW_REFRESH_CHANNEL,
"desktop.ipc.preview.refresh",
(manager, tabId) => manager.refresh(tabId),
);
export const zoomIn = tabMethod(
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
"desktop.ipc.preview.zoomIn",
(manager, tabId) => manager.zoomIn(tabId),
);
export const zoomOut = tabMethod(
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
"desktop.ipc.preview.zoomOut",
(manager, tabId) => manager.zoomOut(tabId),
);
export const resetZoom = tabMethod(
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
"desktop.ipc.preview.resetZoom",
(manager, tabId) => manager.resetZoom(tabId),
);
export const hardReload = tabMethod(
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
"desktop.ipc.preview.hardReload",
(manager, tabId) => manager.hardReload(tabId),
);
export const openDevTools = tabMethod(
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
"desktop.ipc.preview.openDevTools",
(manager, tabId) => manager.openDevTools(tabId),
);
export const cancelPickElement = tabMethod(
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
"desktop.ipc.preview.cancelPickElement",
(manager, tabId) => manager.cancelPickElement(tabId),
);
export const startRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
"desktop.ipc.preview.startRecording",
(manager, tabId) => manager.startRecording(tabId),
);
export const stopRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
"desktop.ipc.preview.stopRecording",
(manager, tabId) => manager.stopRecording(tabId),
);
export const clearCookies = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCookies();
}),
});
export const clearCache = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCache();
}),
});
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
payload: DesktopPreviewConfigInputSchema,
result: DesktopPreviewWebviewConfigSchema,
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.getBrowserSession(environmentId);
return {
partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.setAnnotationTheme(theme);
}),
});
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
}),
});
export const captureScreenshot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: DesktopPreviewScreenshotArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.captureScreenshot(tabId);
}),
});
export const revealArtifact = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.revealArtifact(path);
}),
});
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.copyArtifactToClipboard(path);
}),
});
export const automationStatus = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationStatus,
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationStatus(tabId);
}),
});
export const automationSnapshot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationSnapshot,
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationSnapshot(tabId);
}),
});
export const automationClick = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
payload: DesktopPreviewAutomationClickInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationClick(tabId, input);
}),
});
export const automationType = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
payload: DesktopPreviewAutomationTypeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationType(tabId, input);
}),
});
export const automationPress = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
payload: DesktopPreviewAutomationPressInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationPress(tabId, input);
}),
});
export const automationScroll = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
payload: DesktopPreviewAutomationScrollInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationScroll(tabId, input);
}),
});
export const automationEvaluate = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
payload: DesktopPreviewAutomationEvaluateInputSchema,
result: Schema.Unknown,
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationEvaluate(tabId, input);
}),
});
export const automationWaitFor = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
payload: DesktopPreviewAutomationWaitForInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationWaitFor(tabId, input);
}),
});
export const saveRecording = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
payload: DesktopPreviewRecordingSaveInputSchema,
result: DesktopPreviewRecordingArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.saveRecording(tabId, mimeType, data);
}),
});
export const methods = [
createTab,
closeTab,
registerWebview,
navigate,
goBack,
goForward,
refresh,
zoomIn,
zoomOut,
resetZoom,
hardReload,
openDevTools,
clearCookies,
clearCache,
getPreviewConfig,
setAnnotationTheme,
pickElement,
cancelPickElement,
captureScreenshot,
revealArtifact,
copyArtifactToClipboard,
automationStatus,
automationSnapshot,
automationClick,
automationType,
automationPress,
automationScroll,
automationEvaluate,
automationWaitFor,
startRecording,
stopRecording,
saveRecording,
] as const;
@@ -1,76 +0,0 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
Loaded 100 of 2190 files, more files were not shown because too many files have changed in this diff. Show more