Compare commits
359
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c9a29859b | ||
|
|
6ddeaf0fbb | ||
|
|
4bc7f56330 | ||
|
|
6f34ad3e87 | ||
|
|
62cf461759 | ||
|
|
23c18fda7a | ||
|
|
c0bb237345 | ||
|
|
5d34f9ff23 | ||
|
|
c8a04bd59b | ||
|
|
db4b2d8a0f | ||
|
|
2c199aacac | ||
|
|
8ca4eec9ca | ||
|
|
0936fd271f | ||
|
|
fa69f05b69 | ||
|
|
c710167bde | ||
|
|
a135f2c2d3 | ||
|
|
946b867666 | ||
|
|
0ca3240691 | ||
|
|
f4da4f3b40 | ||
|
|
b6d9ce325c | ||
|
|
8e3467fe60 | ||
|
|
2fae0d0ac3 | ||
|
|
08993a5ec8 | ||
|
|
501ce27b81 | ||
|
|
40c0ab0883 | ||
|
|
33f1cb4224 | ||
|
|
d266c068d0 | ||
|
|
5fcfe242c1 | ||
|
|
df65a6c3ad | ||
|
|
3235658c08 | ||
|
|
749baec353 | ||
|
|
d7baa37e5c | ||
|
|
68ea280388 | ||
|
|
dfbda84362 | ||
|
|
78485e6d50 | ||
|
|
63b6b44627 | ||
|
|
3795dbb017 | ||
|
|
2640e6dcfc | ||
|
|
e34250df46 | ||
|
|
7e1a0d551c | ||
|
|
b511227b7a | ||
|
|
69c8be2ee5 | ||
|
|
271454cbd2 | ||
|
|
e8ff6bc7f8 | ||
|
|
398140a9bd | ||
|
|
2b180a2b2d | ||
|
|
7a820abfdd | ||
|
|
53e3c98a55 | ||
|
|
4f11740510 | ||
|
|
1735e27d9e | ||
|
|
ebe8afb1df | ||
|
|
bf76535fe4 | ||
|
|
5c66110e26 | ||
|
|
da3c2030f7 | ||
|
|
0506508e9b | ||
|
|
b859a575d1 | ||
|
|
e63403fe92 | ||
|
|
c0e161af06 | ||
|
|
d0b9f8d40d | ||
|
|
d8b12ae801 | ||
|
|
31caa5652b | ||
|
|
e350c0a07b | ||
|
|
38e0bb07bb | ||
|
|
765e1b5fc0 | ||
|
|
03e20c875c | ||
|
|
2318e00270 | ||
|
|
4cfec8c128 | ||
|
|
1bd2fa25e2 | ||
|
|
5ca32661b7 | ||
|
|
8b33799523 | ||
|
|
24f9c2a08e | ||
|
|
31ca9e5531 | ||
|
|
73bf127d71 | ||
|
|
43e2aeab38 | ||
|
|
b655a9f183 | ||
|
|
4e3f2f04d5 | ||
|
|
1047dac0c5 | ||
|
|
143b9c9280 | ||
|
|
cf58cadd02 | ||
|
|
6a17629670 | ||
|
|
7b8d12618b | ||
|
|
bcd640bf4d | ||
|
|
b49a2e677c | ||
|
|
ed81c156da | ||
|
|
7dc75127c2 | ||
|
|
e057e2e985 | ||
|
|
a7f6d97b94 | ||
|
|
f9a4f59930 | ||
|
|
7f1cb61031 | ||
|
|
c49d424e3a | ||
|
|
4804a9824f | ||
|
|
0748134cec | ||
|
|
6e9987cf17 | ||
|
|
8b5469863a | ||
|
|
58302b2010 | ||
|
|
1f2797325b | ||
|
|
c14a5ca492 | ||
|
|
eb733c10f2 | ||
|
|
8a02c71861 | ||
|
|
fdca15471d | ||
|
|
5d68fca8f2 | ||
|
|
2a33a18716 | ||
|
|
bde0a4c0dd | ||
|
|
54f167e2e0 | ||
|
|
d114e2772d | ||
|
|
0418301de7 | ||
|
|
5e8b2c800e | ||
|
|
b98233702c | ||
|
|
ecb35f7583 | ||
|
|
d359789ed4 | ||
|
|
462442667e | ||
|
|
c69120f484 | ||
|
|
7b928d5488 | ||
|
|
2fdc704bbb | ||
|
|
3513fa04fb | ||
|
|
735240f316 | ||
|
|
8de254a685 | ||
|
|
c1ec1915fc | ||
|
|
619b0ece94 | ||
|
|
ef943a26ab | ||
|
|
f61fa9499d | ||
|
|
8619ef22e9 | ||
|
|
843cf176ea | ||
|
|
ca1e08b5a0 | ||
|
|
2250e3ee7a | ||
|
|
3201e00ad4 | ||
|
|
e9127658a6 | ||
|
|
18a41388eb | ||
|
|
0c66565854 | ||
|
|
e775bc6228 | ||
|
|
03ac1f0cd9 | ||
|
|
7778a1cea7 | ||
|
|
dad0889766 | ||
|
|
b9cc8d6ef1 | ||
|
|
0e0040832c | ||
|
|
cd8b9fc8b3 | ||
|
|
fa6073e2e1 | ||
|
|
4eb1b57933 | ||
|
|
4414f922fe | ||
|
|
6e42231cb1 | ||
|
|
bdf5aed665 | ||
|
|
0b62e2eb11 | ||
|
|
f9727d0853 | ||
|
|
d8e0ba3ea0 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 | ||
|
|
cabc93bad3 | ||
|
|
5cda815626 | ||
|
|
32d17d3db5 | ||
|
|
6d35a87c5d | ||
|
|
7b9eef7ac2 | ||
|
|
9d66b104fe | ||
|
|
51ea084c87 | ||
|
|
0615fd7df1 | ||
|
|
2448212367 | ||
|
|
fda6486233 | ||
|
|
a9b1190a11 | ||
|
|
44fb34ad53 | ||
|
|
6245c547c2 | ||
|
|
24abab789e | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb | ||
|
|
2a29de7502 | ||
|
|
8c1605b383 | ||
|
|
90074e359f | ||
|
|
6155f5cf64 | ||
|
|
e3970e755b | ||
|
|
3c246f56b4 | ||
|
|
cebbe6ff19 | ||
|
|
e4a84a348e | ||
|
|
61e6d89d69 | ||
|
|
1b2f39d018 | ||
|
|
8c2d33abde | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a | ||
|
|
0488e47d9c | ||
|
|
0eba548282 | ||
|
|
68c0dd3b70 | ||
|
|
4cd958445f | ||
|
|
9f7861aadd | ||
|
|
9243ead1c3 | ||
|
|
803c2b7738 | ||
|
|
28e7c9ae17 | ||
|
|
a9460bb772 | ||
|
|
5edf7c56ba | ||
|
|
90dc76b11e | ||
|
|
57d25c934b | ||
|
|
a26f0dc89f | ||
|
|
6ff6c13fc8 | ||
|
|
60c9ca0e33 | ||
|
|
ad2cb1dd57 | ||
|
|
674590e009 | ||
|
|
f2cb14e774 | ||
|
|
e042c25f56 | ||
|
|
90f1936fad | ||
|
|
42ff43915a | ||
|
|
834e5db458 | ||
|
|
8ce627ba91 | ||
|
|
9a78c6f2ba | ||
|
|
aab72f10c1 | ||
|
|
a76b7bbfb5 | ||
|
|
a51691a9b0 | ||
|
|
97de7d7e15 | ||
|
|
d7718e81e0 | ||
|
|
b88873508e | ||
|
|
58053d146b | ||
|
|
50767683b3 | ||
|
|
d1339f3846 | ||
|
|
faccdd4ca9 | ||
|
|
dd48bfd98c | ||
|
|
6d8d995621 | ||
|
|
b6c590af38 | ||
|
|
b51aef10c4 | ||
|
|
fc2cdeceb9 | ||
|
|
c637dfc454 | ||
|
|
6e9b43cb84 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd | ||
|
|
f1052dd8b1 | ||
|
|
e85144a58c | ||
|
|
defd9dfe20 | ||
|
|
8c03188c1c | ||
|
|
3e5f9f2cdd | ||
|
|
6888276f19 | ||
|
|
e06c33c38d | ||
|
|
5f860439e9 | ||
|
|
c9159b67b3 | ||
|
|
a1b727f62d | ||
|
|
fdc1e8b3a2 | ||
|
|
c8454ad88a | ||
|
|
336d176027 | ||
|
|
204984bf8c | ||
|
|
be4a38e578 | ||
|
|
f50a7cddc1 | ||
|
|
97487d9959 | ||
|
|
d2e38c5373 | ||
|
|
90bd5ee0c1 | ||
|
|
430ece4c0a | ||
|
|
4238a0e769 | ||
|
|
ff0f702c7c | ||
|
|
1cbe8a7a90 | ||
|
|
46fdc769d9 | ||
|
|
0cd0ed1a3d | ||
|
|
d53237cbd1 | ||
|
|
0e718855b8 | ||
|
|
731b1a67ac | ||
|
|
cdfecb36a6 | ||
|
|
f4ef356215 | ||
|
|
d60f5c6101 | ||
|
|
eacceb9e7b | ||
|
|
13a4789a5d | ||
|
|
b6e384fb27 | ||
|
|
d8bf307d22 | ||
|
|
d512deac84 | ||
|
|
32c7f90d9e | ||
|
|
2c16edd0cb | ||
|
|
708bc7091d | ||
|
|
7eb7b4f4a3 | ||
|
|
e01b1903de | ||
|
|
1dc36cef73 | ||
|
|
833c8ab7c6 | ||
|
|
5b1b35c773 | ||
|
|
ee3e2dae78 | ||
|
|
9c98cd60e8 | ||
|
|
48f88d5220 | ||
|
|
2910d9ff01 | ||
|
|
2b8e012924 | ||
|
|
49c23221d8 | ||
|
|
5ca7676661 | ||
|
|
c3e3e26844 | ||
|
|
1486a4a2b9 | ||
|
|
1e5f62801b | ||
|
|
ed6ba7439d | ||
|
|
f98448e872 | ||
|
|
bfe61741b8 | ||
|
|
4d3fcacd84 | ||
|
|
4d790f0064 | ||
|
|
3ecf3685ba | ||
|
|
716ae73c40 | ||
|
|
300d4d566a | ||
|
|
53a477c2e9 | ||
|
|
d84ebe8319 | ||
|
|
5a2c92e86d | ||
|
|
61aade9ea4 | ||
|
|
04f82ae1f3 | ||
|
|
ce0c20b840 | ||
|
|
fccecd8749 | ||
|
|
30a084c463 | ||
|
|
9d5ca2cb7c | ||
|
|
ac77fe452b | ||
|
|
4fbc4f9b20 | ||
|
|
779c237487 | ||
|
|
350e229f7a | ||
|
|
8112aff7c2 | ||
|
|
b9e22de6a3 | ||
|
|
f3b43a148b | ||
|
|
8331511b97 | ||
|
|
08650a7424 | ||
|
|
40d14647db | ||
|
|
cc69aef4dd | ||
|
|
71608142c2 | ||
|
|
bf1a6501c7 | ||
|
|
f7867addbe | ||
|
|
7a8bab5d9d | ||
|
|
06752526b3 | ||
|
|
d87ec967bf | ||
|
|
e55dd0067d | ||
|
|
8c3755aecc | ||
|
|
b4fe8faa1d | ||
|
|
515303edf2 | ||
|
|
20734d4a78 | ||
|
|
86db35ca61 |
No files matched your search
@@ -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."
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including reusable worktree-scoped dev authentication, real 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, exercise real pairing behavior, 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 explicitly labeled `reusable web pairing URL` from the dev-runner 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 so the controlled browser remains the only client surface.
|
||||
|
||||
## Authenticate the browser
|
||||
|
||||
1. Wait for the dev runner's explicitly labeled `reusable web pairing URL`. The server also prints a real one-time pairing URL during startup; do not confuse the two.
|
||||
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 the complete reusable URL 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.
|
||||
|
||||
The reusable development credential is deterministically derived from the canonical worktree path and is intentionally limited to loopback servers. It may be opened repeatedly by browsers testing the same running worktree. Do not mistake it for a production secret or configure it on a remotely reachable server.
|
||||
|
||||
## Exercise real pairing or recover a one-time token
|
||||
|
||||
When the behavior under test is pairing itself, create a real one-time 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.
|
||||
|
||||
Real pairing URLs remain secret, short-lived, and single-use. Do not copy them into final responses, screenshots, committed files, or durable logs.
|
||||
|
||||
## 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 reusable dev URL is rejected, confirm the runner and server use the same worktree and that the backend is loopback-only.
|
||||
- If a real one-time URL was consumed, issue a new token instead of retrying it.
|
||||
- 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`.
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
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.
|
||||
|
||||
For an iOS Simulator or Android Emulator, start the backend through the worktree-aware dev runner after seeding:
|
||||
|
||||
```bash
|
||||
vp run dev:server \
|
||||
--host 127.0.0.1 \
|
||||
--home-dir <base-dir>
|
||||
```
|
||||
|
||||
Keep the process alive and retain the selected server port plus the explicitly labeled reusable iOS and Android pairing URLs. They contain the worktree-scoped development credential and can be retried against this loopback server.
|
||||
|
||||
For a physical device, use the real-pairing path because the reusable development credential is refused on non-loopback hosts:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts serve \
|
||||
--host 0.0.0.0 \
|
||||
--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: 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.
|
||||
|
||||
## Connect a simulator or emulator
|
||||
|
||||
After the development client is running the correct Metro bundle, open the matching reusable URL printed by `vp run dev:server`:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> '<printed-reusable-ios-pairing-url>'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d '<printed-reusable-android-pairing-url>' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Run only the command for the selected platform. The `connections/new` route automatically sends the embedded credential through the normal onboarding exchange; verify that it closes and the expected seeded projects appear. The reusable development URL may be reopened after resetting the client connection.
|
||||
|
||||
## Pair a physical device or test real pairing
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Real pairing credentials are secret, short-lived, and single-use. Create a different credential for every physical device or real-pairing test client. 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 simulator or emulator cannot reconnect:** reopen the platform-specific reusable URL and confirm the backend is still loopback-only.
|
||||
- **A physical or real-pairing 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."
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../.agents/skills
|
||||
@@ -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"
|
||||
@@ -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,6 +18,10 @@
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
|
||||
@@ -57,7 +57,10 @@ jobs:
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
packager: pnpm
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -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
|
||||
@@ -252,10 +252,64 @@ jobs:
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
|
||||
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
|
||||
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
|
||||
# job — the Windows artifact then ships a ready WSL backend binary with no
|
||||
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
needs: [preflight]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Resolve node-pty from apps/server (where it's a dependency) and build
|
||||
# its native binary from source for Linux. node-addon-api resolves from
|
||||
# node-pty's own dependency tree, so node-gyp has everything it needs.
|
||||
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
|
||||
pty_dir="$(dirname "$pty_pkg")"
|
||||
( cd "$pty_dir" && npx --yes node-gyp rebuild )
|
||||
mkdir -p wsl-prebuild
|
||||
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
|
||||
file wsl-prebuild/pty.node
|
||||
|
||||
- name: Upload node-pty linux-x64 prebuild
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild/pty.node
|
||||
if-no-files-found: error
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: [preflight, relay_public_config]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
|
||||
# available to download, but only the Windows matrix entry consumes it. We
|
||||
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
|
||||
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
|
||||
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
|
||||
# build_wsl_node_pty failed; the Windows-only download step below then fails
|
||||
# that single platform if the prebuild is missing.
|
||||
needs: [preflight, relay_public_config, build_wsl_node_pty]
|
||||
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -323,6 +377,13 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Download WSL node-pty prebuild
|
||||
if: matrix.platform == 'win'
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
@@ -476,6 +537,10 @@ jobs:
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
|
||||
# so the packaged WSL backend ships a ready binary (no first-launch
|
||||
# compile). Required for a working WSL backend on Windows.
|
||||
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
@@ -723,6 +788,7 @@ jobs:
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
@@ -806,6 +872,7 @@ jobs:
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=${T3CODE_CLERK_CLI_OAUTH_CLIENT_ID:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
|
||||
@@ -27,6 +27,9 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -43,12 +43,23 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Dependency acquisition and runtime boundaries
|
||||
|
||||
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
|
||||
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
|
||||
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -56,6 +67,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -73,4 +87,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"xcodebuildmcp": {
|
||||
"command": "npx",
|
||||
"args": ["--yes", "[email protected]", "mcp"],
|
||||
"env": {
|
||||
"XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>T3 Code — Agent-Friendly Development Authentication</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--text: #fff;
|
||||
--muted: #a3a3a3;
|
||||
--surface: #101010;
|
||||
--surface-2: #171717;
|
||||
--line: #292929;
|
||||
--green: #55e6a5;
|
||||
--blue: #67b7ff;
|
||||
--amber: #f4c65d;
|
||||
--red: #ff7d7d;
|
||||
--radius: 14px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior: smooth; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.6 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
main { width: min(1120px, calc(100% - 32px)); margin: 0 auto; padding: 64px 0 96px; }
|
||||
h1, h2, h3 { margin: 0; line-height: 1.15; letter-spacing: -0.025em; }
|
||||
h1 { max-width: 850px; font-size: clamp(2.4rem, 7vw, 5.4rem); }
|
||||
h2 { font-size: clamp(1.5rem, 3vw, 2.25rem); }
|
||||
h3 { font-size: 1rem; letter-spacing: 0; }
|
||||
p { margin: 0; }
|
||||
code {
|
||||
color: #dff7eb;
|
||||
font: 0.9em ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
}
|
||||
pre {
|
||||
margin: 0;
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: #080808;
|
||||
color: #dff7eb;
|
||||
font: 13px/1.65 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
}
|
||||
section { margin-top: 72px; }
|
||||
.eyebrow {
|
||||
margin-bottom: 18px;
|
||||
color: var(--green);
|
||||
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
letter-spacing: 0.16em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.lede { max-width: 760px; margin-top: 24px; color: #d4d4d4; font-size: 1.15rem; }
|
||||
.meta { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 28px; }
|
||||
.pill {
|
||||
padding: 7px 11px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.pill strong { color: var(--text); }
|
||||
.callout {
|
||||
margin-top: 32px;
|
||||
padding: 22px;
|
||||
border: 1px solid #245d45;
|
||||
border-radius: var(--radius);
|
||||
background: #07150f;
|
||||
}
|
||||
.callout strong { color: var(--green); }
|
||||
.section-head { display: grid; gap: 10px; max-width: 740px; margin-bottom: 26px; }
|
||||
.section-head p { color: var(--muted); }
|
||||
.grid { display: grid; gap: 16px; }
|
||||
.grid.three { grid-template-columns: repeat(3, 1fr); }
|
||||
.grid.two { grid-template-columns: repeat(2, 1fr); }
|
||||
.card {
|
||||
padding: 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
.card p { margin-top: 9px; color: var(--muted); }
|
||||
.card .number {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
margin-bottom: 18px;
|
||||
border-radius: 50%;
|
||||
background: var(--text);
|
||||
color: var(--bg);
|
||||
font-weight: 800;
|
||||
}
|
||||
.command-grid { display: grid; grid-template-columns: 170px 1fr; gap: 1px; overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius); background: var(--line); }
|
||||
.command-grid > div { padding: 14px 16px; background: var(--surface); }
|
||||
.command-grid .label { color: var(--muted); }
|
||||
.diagram {
|
||||
overflow-x: auto;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
.diagram svg { display: block; min-width: 840px; width: 100%; height: auto; }
|
||||
.steps { counter-reset: step; display: grid; gap: 14px; }
|
||||
.step {
|
||||
position: relative;
|
||||
padding: 20px 20px 20px 66px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
.step::before {
|
||||
counter-increment: step;
|
||||
content: counter(step);
|
||||
position: absolute;
|
||||
top: 18px;
|
||||
left: 20px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
background: var(--surface-2);
|
||||
color: var(--green);
|
||||
font-weight: 800;
|
||||
}
|
||||
.step p { margin-top: 7px; color: var(--muted); }
|
||||
.file-list { display: grid; gap: 8px; }
|
||||
.file {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(230px, 0.8fr) 1.2fr;
|
||||
gap: 18px;
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.file:last-child { border-bottom: 0; }
|
||||
.file span { color: var(--muted); }
|
||||
.checklist { display: grid; gap: 10px; margin: 0; padding: 0; list-style: none; }
|
||||
.checklist li { position: relative; padding-left: 30px; color: #d4d4d4; }
|
||||
.checklist li::before { content: "✓"; position: absolute; left: 0; color: var(--green); font-weight: 800; }
|
||||
.warning { border-color: #5b4820; background: #161105; }
|
||||
.warning strong { color: var(--amber); }
|
||||
.not-doing { color: var(--red); }
|
||||
footer { margin-top: 80px; padding-top: 22px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }
|
||||
|
||||
@media (max-width: 820px) {
|
||||
main { padding-top: 40px; }
|
||||
section { margin-top: 52px; }
|
||||
.grid.three, .grid.two { grid-template-columns: 1fr; }
|
||||
.command-grid, .file { grid-template-columns: 1fr; }
|
||||
.command-grid .label { padding-bottom: 6px; }
|
||||
.file { gap: 4px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<div class="eyebrow">Implementation plan · T3 Code</div>
|
||||
<h1>Development auth that agents never have to think about.</h1>
|
||||
<p class="lede">
|
||||
Derive a reusable development key from the canonical worktree path, print it in ordinary
|
||||
pairing URLs, and let the existing browser and mobile pairing flows do the rest.
|
||||
</p>
|
||||
<div class="meta">
|
||||
<span class="pill"><strong>Scope:</strong> web, iOS Simulator, Android Emulator</span>
|
||||
<span class="pill"><strong>Boundary:</strong> explicit, loopback-only development mode</span>
|
||||
<span class="pill"><strong>Steady state:</strong> existing sessions and WebSocket tickets</span>
|
||||
</div>
|
||||
<div class="callout">
|
||||
<strong>Core decision:</strong> the path-derived value is a development instance key, not a secret.
|
||||
It may appear in development pairing URLs. Its value is unlimited reuse, not secrecy.
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Target experience</div>
|
||||
<h2>Keep the commands agents already use</h2>
|
||||
<p>The runner prepares the server and prints reusable web, iOS, and Android connection URLs; the testing skills continue to own browsers, Metro, simulators, and emulators.</p>
|
||||
</div>
|
||||
<div class="command-grid" role="table" aria-label="Development commands">
|
||||
<div class="label">Web stack</div><div><code>vp run dev --home-dir <base-dir></code></div>
|
||||
<div class="label">Mobile backend</div><div><code>vp run dev:server --home-dir <base-dir> --host 127.0.0.1</code></div>
|
||||
<div class="label">Mobile client</div><div><span class="label">Reuse/start Metro and drive the selected device with </span><code>test-t3-mobile</code></div>
|
||||
<div class="label">Physical device</div><div><span class="label">Use existing real pairing; the development key is never accepted on a LAN bind.</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Architecture</div>
|
||||
<h2>A bootstrap, not a bypass</h2>
|
||||
<p>The only new server behavior is a reusable, loopback-only grant. Existing pairing screens and token exchanges remain the client implementation.</p>
|
||||
</div>
|
||||
<div class="diagram">
|
||||
<svg viewBox="0 0 1000 330" role="img" aria-labelledby="diagram-title diagram-desc">
|
||||
<title id="diagram-title">Development authentication flow</title>
|
||||
<desc id="diagram-desc">The dev runner derives a key, seeds it on the server, prints an ordinary reusable pairing URL, and the existing client pairing flow exchanges it for a normal session.</desc>
|
||||
<defs>
|
||||
<marker id="arrow" markerWidth="9" markerHeight="9" refX="8" refY="4.5" orient="auto">
|
||||
<path d="M0,0 L9,4.5 L0,9 Z" fill="#67b7ff" />
|
||||
</marker>
|
||||
</defs>
|
||||
<rect x="30" y="80" width="210" height="150" rx="16" fill="#171717" stroke="#3a3a3a" />
|
||||
<text x="55" y="116" fill="#55e6a5" font-size="14" font-weight="700">DEV RUNNER</text>
|
||||
<text x="55" y="151" fill="#fff" font-size="18" font-weight="700">Canonical Git root</text>
|
||||
<text x="55" y="180" fill="#a3a3a3" font-size="14">realpath → SHA-256</text>
|
||||
<text x="55" y="207" fill="#a3a3a3" font-size="14">print reusable pair URLs</text>
|
||||
|
||||
<rect x="395" y="25" width="230" height="120" rx="16" fill="#171717" stroke="#3a3a3a" />
|
||||
<text x="420" y="60" fill="#67b7ff" font-size="14" font-weight="700">SERVER</text>
|
||||
<text x="420" y="91" fill="#fff" font-size="17" font-weight="700">Reusable dev grant</text>
|
||||
<text x="420" y="120" fill="#a3a3a3" font-size="14">administrative bootstrap scopes</text>
|
||||
|
||||
<rect x="395" y="185" width="230" height="120" rx="16" fill="#171717" stroke="#3a3a3a" />
|
||||
<text x="420" y="220" fill="#f4c65d" font-size="14" font-weight="700">CLIENT</text>
|
||||
<text x="420" y="251" fill="#fff" font-size="17" font-weight="700">Existing pair flow</text>
|
||||
<text x="420" y="280" fill="#a3a3a3" font-size="14">browser or mobile deep link</text>
|
||||
|
||||
<rect x="775" y="80" width="195" height="150" rx="16" fill="#07150f" stroke="#245d45" />
|
||||
<text x="800" y="116" fill="#55e6a5" font-size="14" font-weight="700">STEADY STATE</text>
|
||||
<text x="800" y="151" fill="#fff" font-size="17" font-weight="700">Normal session</text>
|
||||
<text x="800" y="180" fill="#a3a3a3" font-size="14">cookie / bearer / DPoP</text>
|
||||
<text x="800" y="207" fill="#a3a3a3" font-size="14">existing WS tickets</text>
|
||||
|
||||
<path d="M240 125 H380" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
|
||||
<path d="M240 190 C300 190 320 245 380 245" fill="none" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
|
||||
<path d="M625 245 C700 245 690 185 760 185" fill="none" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
|
||||
<path d="M625 86 H760" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
|
||||
<text x="654" y="72" fill="#a3a3a3" font-size="12">accept key</text>
|
||||
<text x="658" y="266" fill="#a3a3a3" font-size="12">issue session</text>
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Implementation</div>
|
||||
<h2>Four small changes</h2>
|
||||
</div>
|
||||
<div class="steps">
|
||||
<article class="step">
|
||||
<h3>Derive and print one stable development key</h3>
|
||||
<p>Resolve the canonical Git worktree root and compute <code>sha256("t3-dev:" + realpath(root))</code>. The runner exports <code>T3CODE_DEV_AUTH=1</code> and <code>T3CODE_DEV_AUTH_KEY</code> to its server child, then prints a reusable web pairing URL plus separate iOS and Android connection deep links containing the same key.</p>
|
||||
</article>
|
||||
<article class="step">
|
||||
<h3>Seed a reusable server bootstrap grant</h3>
|
||||
<p>Read the two environment variables in server configuration. When explicitly enabled on a loopback bind, seed the key with administrative bootstrap scopes and unlimited exchanges for the process lifetime. Refuse dev auth for wildcard or non-loopback hosts.</p>
|
||||
</article>
|
||||
<article class="step">
|
||||
<h3>Use existing clients with one tiny mobile adapter</h3>
|
||||
<p>Web requires no changes: opening <code>/pair#token=…</code> already creates its cookie session. Mobile accepts the printed host and credential on the existing <code>connections/new</code> route and forwards them to current connection onboarding.</p>
|
||||
</article>
|
||||
<article class="step">
|
||||
<h3>Simplify the testing skills</h3>
|
||||
<p>The web skill opens the reusable URL exactly as it opens today’s one-time URL. The mobile skill keeps responsibility for Metro reuse, device selection, and platform-specific origins, then opens the printed deep link. Real one-time pairing remains the physical-device and auth-test path.</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Likely touchpoints</div>
|
||||
<h2>Keep the change narrow</h2>
|
||||
</div>
|
||||
<div class="card file-list">
|
||||
<div class="file"><code>scripts/dev-runner.ts</code><span>Derive/export the key and print reusable web/mobile connection information. Do not orchestrate devices.</span></div>
|
||||
<div class="file"><code>apps/server/src/cli/config.ts</code><span>Read the explicit dev-auth configuration.</span></div>
|
||||
<div class="file"><code>apps/server/src/config.ts</code><span>Carry the dev-auth key and enabled state.</span></div>
|
||||
<div class="file"><code>apps/server/src/auth/PairingGrantStore.ts</code><span>Seed the reusable grant using the existing desktop pattern and enforce loopback-only use.</span></div>
|
||||
<div class="file"><code>apps/server/src/auth/utils.ts</code><span>Namespace development cookies by server port.</span></div>
|
||||
<div class="file"><code>apps/mobile/src/Stack.tsx</code><span>Accept host and credential parameters on the existing connections route.</span></div>
|
||||
<div class="file"><code>apps/mobile/src/connection/onboarding.ts</code><span>Feed the development deep link into existing pairing onboarding.</span></div>
|
||||
<div class="file"><code>.agents/skills/test-t3-app/SKILL.md</code><span>Open the reusable dev pairing URL; keep one-time recovery for real-auth tests.</span></div>
|
||||
<div class="file"><code>.agents/skills/test-t3-mobile/SKILL.md</code><span>Use dev:server output for simulators/emulators; keep real pairing for physical devices.</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Guardrails</div>
|
||||
<h2>Deliberately unsafe, tightly contained</h2>
|
||||
</div>
|
||||
<div class="grid three">
|
||||
<article class="card">
|
||||
<h3>Explicit activation</h3>
|
||||
<p>The server accepts the key only when <code>T3CODE_DEV_AUTH=1</code>. Production defaults never infer it from the filesystem.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h3>Loopback only</h3>
|
||||
<p>The server refuses this guessable key on wildcard, LAN, Tailnet, or other non-loopback binds. Physical-device verification uses real pairing.</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h3>Real auth coexists</h3>
|
||||
<p>Existing startup pairing output and <code>auth pairing create</code> remain available. No special <code>--auth real</code> mode is needed.</p>
|
||||
</article>
|
||||
</div>
|
||||
<div class="callout warning">
|
||||
<strong>The key is intentionally public.</strong> It may appear in terminal output and development URLs. Never substitute <code>T3_MCP_BEARER_TOKEN</code>, which authorizes agent MCP access.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Verification</div>
|
||||
<h2>Acceptance checklist</h2>
|
||||
</div>
|
||||
<div class="grid two">
|
||||
<article class="card">
|
||||
<h3>Focused automated coverage</h3>
|
||||
<ul class="checklist">
|
||||
<li>Same canonical worktree produces the same key.</li>
|
||||
<li>Different worktrees produce different keys.</li>
|
||||
<li>The dev grant supports repeated exchange.</li>
|
||||
<li>A mismatched or absent key is rejected.</li>
|
||||
<li>Non-loopback dev auth is rejected.</li>
|
||||
<li>Production behavior is unchanged.</li>
|
||||
<li>Parallel dev cookies do not collide.</li>
|
||||
<li>Mobile deep-link registration is idempotent.</li>
|
||||
</ul>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h3>Integrated proof</h3>
|
||||
<ul class="checklist">
|
||||
<li>Run one isolated web environment and open its printed reusable pairing URL.</li>
|
||||
<li>Open that URL again in a fresh browser context and confirm both exchanges succeed.</li>
|
||||
<li>Run one representative iOS Simulator or Android Emulator environment.</li>
|
||||
<li>Start/reuse Metro with the mobile skill and open the printed connection deep link.</li>
|
||||
<li>Confirm seeded projects load from the intended backend.</li>
|
||||
<li>Confirm a LAN-bound backend falls back to real one-time pairing.</li>
|
||||
<li>Stop all owned processes and clean disposable state.</li>
|
||||
</ul>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<div class="eyebrow">Non-goals</div>
|
||||
<h2>What this plan avoids</h2>
|
||||
</div>
|
||||
<div class="card">
|
||||
<ul class="checklist">
|
||||
<li><span class="not-doing">No</span> custom authorization header on every request.</li>
|
||||
<li><span class="not-doing">No</span> alternate WebSocket authentication protocol.</li>
|
||||
<li><span class="not-doing">No</span> persisted development secret or token recovery workflow.</li>
|
||||
<li><span class="not-doing">No</span> Vite, web-auth bootstrap, or mobile bundle configuration changes.</li>
|
||||
<li><span class="not-doing">No</span> new runner flag for device selection or lifecycle.</li>
|
||||
<li><span class="not-doing">No</span> changes to desktop, whose reusable bootstrap already works.</li>
|
||||
<li><span class="not-doing">No</span> weakening of production pairing, scopes, sessions, or DPoP.</li>
|
||||
<li><span class="not-doing">No</span> automatic native rebuild when a compatible dev client already exists.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
Proposed implementation order: runner key and URLs → loopback-only reusable server grant → mobile route adapter → skill updates → focused integrated verification.
|
||||
</footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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 — every step reuses code that already exists. One PR, built as four phases with clear commit boundaries — 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>
|
||||
<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 — 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 — <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 — <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 — <strong>untouched</strong></li>
|
||||
<li>Existing subcommands <code>login/link/status/unlink/logout</code> — 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 — t3 CLI</text>
|
||||
<text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop — 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#{state,challenge}</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 → /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&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 {code + verifier} → 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 → Connected!</text>
|
||||
</svg>
|
||||
<figcaption>The verifier never leaves the box (steps 1→7), so the authorization code is worthless if observed. state/challenge ride the URL fragment — 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 — 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@…") 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 — the same timeout the existing loopback flow already uses. Wrong/expired code → 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–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 — 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 — 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> — nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop — 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 — Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/<v></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 — systemd user units fail invisibly otherwise. Unit-file generation is pure string-building → 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 < latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command — client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified — that would be RCE). Stage install → verify → atomic symlink swap → <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/ ← npm install --prefix (gets native deps right: node-pty etc.)
|
||||
└── current -> versions/0.0.27
|
||||
|
||||
~/.config/systemd/user/t3code.service ← ExecStart=/abs/path/node .../current/.../t3 serve
|
||||
loginctl enable-linger $USER ← 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">✗</span> Relay / <code>infra</code> / contracts changes — none, in any phase</li>
|
||||
<li><span class="no">✗</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) — only matters for hand-typing; revisit if ever needed</li>
|
||||
<li><span class="no">✗</span> RFC 8628 device grant — wrong UX direction, unverified Clerk support</li>
|
||||
<li><span class="no">✗</span> Auto-update loop in the daemon — web-triggered only (phase 4 follow-up), user stays in control</li>
|
||||
<li><span class="no">✗</span> Project auto-registration — workspace assumed set up; the web UI handles the rest</li>
|
||||
<li><span class="no">✗</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
|
||||
</ul>
|
||||
|
||||
<h2>Risks & checks</h2>
|
||||
<ul>
|
||||
<li><span class="warn">⚠</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">⚠</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 — hence the phase 3 requirement to log to a printed file path.</li>
|
||||
<li><span class="warn">⚠</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on — that's the feature, but say it.</li>
|
||||
<li><span class="ok">✓</span> Re-running <code>connect</code> when linked → 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) — 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>
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
vp staged
|
||||
@@ -2,27 +2,16 @@
|
||||
|
||||
## 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.
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
|
||||
## 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.
|
||||
- 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.
|
||||
|
||||
## Package Roles
|
||||
|
||||
@@ -35,7 +24,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 +35,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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.27",
|
||||
"version": "0.0.28",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -31,7 +31,7 @@
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"electron-builder": "26.15.6",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
|
||||
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -204,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
@@ -261,11 +278,25 @@ function readJson(path) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
|
||||
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
@@ -282,12 +313,19 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
NodeFS.existsSync(launcherBinaryPath) &&
|
||||
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
@@ -299,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchMainBundleInfoPlist(
|
||||
targetAppBundlePath,
|
||||
iconPath,
|
||||
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
|
||||
);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
// Keep Electron's native executable inside the branded bundle. Launching the
|
||||
// node_modules copy makes macOS associate the process (and Dock label) with
|
||||
// Electron.app even though this bundle's Info.plist has the T3 Code name.
|
||||
// Its conventional executable name also keeps Electron's default-app runtime
|
||||
// in development mode instead of making app.isPackaged report true.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
@@ -336,10 +383,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
@@ -356,13 +400,23 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveElectronBinaryPath({
|
||||
ensureRuntime = ensureElectronRuntime,
|
||||
createRequire = NodeModule.createRequire,
|
||||
moduleUrl = import.meta.url,
|
||||
} = {}) {
|
||||
ensureRuntime();
|
||||
|
||||
const require = createRequire(moduleUrl);
|
||||
return require("electron");
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
|
||||
it("repairs Electron before loading the package entrypoint", () => {
|
||||
const calls = [];
|
||||
const electronPath = resolveElectronBinaryPath({
|
||||
ensureRuntime: () => {
|
||||
calls.push("ensure");
|
||||
},
|
||||
createRequire: () => (specifier) => {
|
||||
calls.push(`require:${specifier}`);
|
||||
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
|
||||
},
|
||||
moduleUrl: import.meta.url,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
electronPath,
|
||||
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
|
||||
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
|
||||
const paths = resolveMacLauncherPaths(
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
|
||||
"T3 Code (Dev)",
|
||||
);
|
||||
|
||||
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
|
||||
assert.equal(
|
||||
paths.launcherBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
|
||||
);
|
||||
assert.equal(
|
||||
paths.runtimeElectronBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
|
||||
);
|
||||
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: paths.runtimeElectronBinaryPath,
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {},
|
||||
});
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -13,7 +13,8 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
@@ -23,6 +24,7 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
@@ -33,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.";
|
||||
}
|
||||
}
|
||||
@@ -133,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)) {
|
||||
@@ -191,8 +198,20 @@ const bootstrap = Effect.gen(function* () {
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
yield* backendManager.start;
|
||||
// In wsl-only mode the renderer is served by the WSL backend, which can be
|
||||
// slow to cold-boot — show a "Connecting to WSL" splash immediately so the
|
||||
// app feels responsive instead of presenting no window until WSL is ready.
|
||||
// (Dual mode opens fast off the Windows primary, so no splash there.)
|
||||
if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
}
|
||||
yield* primaryBackend.start;
|
||||
yield* logBootstrapInfo("bootstrap backend start requested");
|
||||
// Bring up the WSL backend if the user previously enabled it. The
|
||||
// primary is already starting; reconcile fires off the WSL register
|
||||
// in parallel rather than blocking primary readiness on a possibly
|
||||
// slow first wsl.exe spawn.
|
||||
yield* Effect.forkScoped(wslBackend.reconcile);
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.bootstrap"));
|
||||
|
||||
@@ -239,10 +258,20 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
// Stop every backend in the pool, not just the primary. The
|
||||
// electronApp.quit() path can race ahead of the layer-scope
|
||||
// cascade, so leaving the WSL instance for its parent scope
|
||||
// finalizer means it gets hard-killed by the OS instead of
|
||||
// receiving SIGTERM + grace. Stops run concurrently.
|
||||
const instances = yield* pool.list;
|
||||
yield* Effect.forEach(instances, (instance) => instance.stop(), {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
}).pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
);
|
||||
|
||||
yield* startup;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -18,10 +18,22 @@ const AppPackageMetadata = Schema.Struct({
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
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,
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
@@ -33,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;
|
||||
@@ -83,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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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,11 +13,26 @@ export interface DesktopIconPaths {
|
||||
readonly png: 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,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
readonly resolveResourcePath: (
|
||||
fileName: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
|
||||
@@ -24,14 +40,20 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
|
||||
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);
|
||||
}
|
||||
@@ -43,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 && 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);
|
||||
}
|
||||
@@ -61,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
|
||||
>();
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLog.of(service);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendOutputLog, make);
|
||||
@@ -1,7 +1,8 @@
|
||||
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 { vi } from "vite-plus/test";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
@@ -24,7 +25,23 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
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$")}`;
|
||||
|
||||
@@ -40,19 +57,9 @@ describe("DesktopClerk", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment: true,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(
|
||||
Layer.build(
|
||||
DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
@@ -69,6 +76,54 @@ describe("DesktopClerk", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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" },
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
@@ -14,6 +15,32 @@ 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,
|
||||
{
|
||||
@@ -55,11 +82,28 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
|
||||
(bridge) => Effect.sync(() => bridge.cleanup()),
|
||||
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({
|
||||
|
||||
@@ -393,7 +393,21 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
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),
|
||||
|
||||
@@ -53,8 +53,6 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
@@ -62,8 +60,12 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
@@ -78,17 +80,6 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
@@ -142,18 +133,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
|
||||
}
|
||||
}
|
||||
|
||||
const migrationError = (
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: string,
|
||||
cause: unknown,
|
||||
environmentId?: string,
|
||||
): DesktopConnectionCatalogStoreMigrationError =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation,
|
||||
catalogPath,
|
||||
...(environmentId === undefined ? {} : { environmentId }),
|
||||
cause,
|
||||
});
|
||||
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,
|
||||
@@ -164,13 +155,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
@@ -236,20 +227,46 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
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) => writeError("encode-document", input.catalogPath, cause)),
|
||||
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* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.catalogPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
|
||||
);
|
||||
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(
|
||||
@@ -330,13 +347,17 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments
|
||||
.getSecret(record.environmentId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
|
||||
),
|
||||
);
|
||||
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,
|
||||
@@ -362,13 +383,41 @@ export const make = Effect.gen(function* () {
|
||||
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));
|
||||
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) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
@@ -380,21 +429,42 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
|
||||
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) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
@@ -405,16 +475,27 @@ export const make = Effect.gen(function* () {
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
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* safeStorage.isEncryptionAvailable)) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
|
||||
@@ -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,13 +53,16 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, true);
|
||||
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
|
||||
assert.equal(environment.baseDir, "/tmp/t3");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/dev");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
|
||||
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
|
||||
assert.equal(
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
"/tmp/t3/userdata/saved-environments.json",
|
||||
);
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
it.effect("stores production state under userdata in an explicit home", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -95,6 +98,19 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps implicit development state separate from production state", () =>
|
||||
Effect.gen(function* () {
|
||||
const development = yield* makeEnvironment(
|
||||
{},
|
||||
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
|
||||
);
|
||||
const production = yield* makeEnvironment();
|
||||
|
||||
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
|
||||
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses a configured app user model id override", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
|
||||
@@ -147,7 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const stateDir = path.join(
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
@@ -15,6 +15,18 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
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 type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
@@ -61,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
function* (): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
|
||||
> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
@@ -142,11 +160,10 @@ export const make = DesktopLifecycle.of({
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
const error = new DesktopLifecycleRelaunchError({ reason, cause });
|
||||
return logLifecycleError(error.message, { error });
|
||||
}),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,20 +1,65 @@
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
// a writer that targets a distinct rotating log file — the primary
|
||||
// instance keeps `server-child.log` so the historical path stays stable
|
||||
// for ops; other instances get `server-child-<sanitized-id>.log`.
|
||||
//
|
||||
// Writers are cached per id within a single factory instance so repeated
|
||||
// `forInstance` calls (e.g. during a backend restart that re-resolves
|
||||
// services) reuse the same rotating writer rather than racing each other
|
||||
// on the same file.
|
||||
export class DesktopBackendOutputLogFactory extends Context.Service<
|
||||
DesktopBackendOutputLogFactory,
|
||||
{
|
||||
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
export type DesktopLogAnnotations = Record<string, unknown>;
|
||||
|
||||
@@ -50,7 +95,166 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
|
||||
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
|
||||
|
||||
const DesktopBackendChildLogRecord = Schema.Struct({
|
||||
message: Schema.String,
|
||||
level: Schema.Literals(["INFO", "ERROR"]),
|
||||
timestamp: Schema.String,
|
||||
annotations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
spans: Schema.Record(Schema.String, Schema.Unknown),
|
||||
fiberId: Schema.String,
|
||||
});
|
||||
|
||||
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendChildLogRecord),
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
};
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
|
||||
});
|
||||
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
}): Effect.fn.Return<
|
||||
RotatingLogFileWriter,
|
||||
DesktopLogFileWriterError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
|
||||
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
|
||||
const directory = path.dirname(input.filePath);
|
||||
const baseName = path.basename(input.filePath);
|
||||
|
||||
if (maxBytes < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxBytes",
|
||||
value: maxBytes,
|
||||
});
|
||||
}
|
||||
if (maxFiles < 1) {
|
||||
return yield* new DesktopLogFileWriterConfigurationError({
|
||||
option: "maxFiles",
|
||||
value: maxFiles,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
|
||||
const withSuffix = (index: number) => `${input.filePath}.${index}`;
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const beforeSize = yield* Ref.get(currentSize);
|
||||
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
|
||||
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
|
||||
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
|
||||
yield* Ref.set(currentSize, afterSize);
|
||||
|
||||
if (afterSize > maxBytes) {
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
});
|
||||
|
||||
const readPersistedOtlpTracesUrl: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
@@ -70,6 +274,170 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
|
||||
return yield* readPersistedOtlpTracesUrl;
|
||||
});
|
||||
|
||||
const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
logFile: RotatingLogFileWriter,
|
||||
input: {
|
||||
readonly message: string;
|
||||
readonly level: "INFO" | "ERROR";
|
||||
readonly annotations: Record<string, unknown>;
|
||||
},
|
||||
): Effect.fn.Return<void> {
|
||||
return yield* Effect.gen(function* () {
|
||||
const timestamp = DateTime.formatIso(yield* DateTime.now);
|
||||
const encoded = yield* encodeDesktopBackendChildLogRecord({
|
||||
message: input.message,
|
||||
level: input.level,
|
||||
timestamp,
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
|
||||
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
||||
|
||||
const backendLogFilePathForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): string => {
|
||||
// Primary keeps the historical "server-child.log" path so ops scripts
|
||||
// and packaged-build log inspection still find it where it always lived.
|
||||
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}
|
||||
const sanitized = sanitizeInstanceIdForFileName(id);
|
||||
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
|
||||
};
|
||||
|
||||
// Just the IO sink. Cacheable by resolved file path so two ids that
|
||||
// sanitize to the same filename share a single RotatingLogFileWriter
|
||||
// (no race on currentSize tracking). Splitting the sink off from the
|
||||
// per-call shape lets the shape annotate writes with the *caller's*
|
||||
// id rather than whatever id created the cached writer first.
|
||||
const makeBackendOutputSinkForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<RotatingLogFileWriter>,
|
||||
never,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope
|
||||
> =>
|
||||
makeRotatingLogFileWriter({
|
||||
filePath: backendLogFilePathForInstance(environment, id),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
DesktopBackendOutputLogFactory,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const factoryScope = yield* Scope.Scope;
|
||||
// Per-file-path cache of the IO sink only. The per-call shape
|
||||
// wraps the sink with the caller's instance id so a cache hit on
|
||||
// a path collision (e.g. "wsl:default" and "wsl_default" both
|
||||
// resolve to server-child-wsl_default.log) doesn't attribute the
|
||||
// second caller's writes to the first caller's id. Each sink pins
|
||||
// itself to the factory's scope so all log resources tear down
|
||||
// together at app exit. Mutex serializes concurrent first-time
|
||||
// lookups for the same file path.
|
||||
const cacheRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
|
||||
>(new Map());
|
||||
|
||||
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Scope.provide(factoryScope),
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLogFactory.of({
|
||||
forInstance: (id) => makeForId(id),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopLoggerLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
@@ -82,8 +450,8 @@ const tracerLayer = Layer.unwrap(
|
||||
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: tracePath,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
});
|
||||
const delegate = Option.isNone(otlpTracesUrl)
|
||||
@@ -101,8 +469,8 @@ const tracerLayer = Layer.unwrap(
|
||||
});
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: tracePath,
|
||||
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
|
||||
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
|
||||
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
|
||||
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
@@ -113,7 +481,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
DesktopBackendOutputLogModule.layer,
|
||||
backendOutputLogFactoryLayer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -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({
|
||||
@@ -39,19 +51,22 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
platform: options?.platform ?? "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
appPath: options?.appPath ?? "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: "/missing/resources",
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -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,20 +9,57 @@ 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 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,
|
||||
{
|
||||
readonly resolve: Effect.Effect<
|
||||
// Build the Windows-native primary backend's start config. Reads the
|
||||
// primary's port/host/exposure from DesktopServerExposure. Can fail
|
||||
// with PlatformError because bootstrap token generation now uses
|
||||
// crypto.randomBytes under the hood (post Effect 4 migration).
|
||||
readonly resolvePrimary: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// Build a WSL backend start config for the given distro on the given
|
||||
// port. The WSL backend is always loopback-only (the primary owns LAN
|
||||
// exposure when the user opts in), so this takes the port directly and
|
||||
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
|
||||
// forwarded to wsl.exe with no -d flag.
|
||||
readonly resolveWsl: (input: {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
}) => Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// The renderer-facing label for the primary instance, derived from the
|
||||
// same decision resolvePrimary makes (including the WSL-availability
|
||||
// fall-back to Windows), so the env switcher can't show "WSL" for a
|
||||
// backend that actually resolved to Windows.
|
||||
readonly resolvePrimaryLabel: Effect.Effect<string>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
@@ -47,28 +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 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;
|
||||
}
|
||||
|
||||
@@ -79,11 +166,168 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}): Effect.fn.Return<
|
||||
interface SharedBootstrapInput {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}
|
||||
|
||||
interface WslPreflightSuccess {
|
||||
readonly _tag: "Ready";
|
||||
readonly runningDistro: string;
|
||||
readonly linuxEntryPath: string;
|
||||
// Absolute path to the node binary the preflight validated after the shared
|
||||
// remote resolver repaired PATH. The launch must use this exact path so it
|
||||
// doesn't fall through to a different/old node than the one node-pty was
|
||||
// built against.
|
||||
readonly nodePath: string;
|
||||
// PATH captured from the same login shell after the shared resolver loaded
|
||||
// version managers. The launch forwards this value directly without a shell.
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
|
||||
interface WslPreflightFailure {
|
||||
readonly _tag: "Failed";
|
||||
readonly reason: string;
|
||||
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
|
||||
// build tools) and retrying won't help — surface it and (wsl-only) fall back
|
||||
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
|
||||
// boots), with a bounded window for self-healing before fallback.
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
}
|
||||
|
||||
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
|
||||
|
||||
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
readonly windowsEntryPath: string;
|
||||
readonly windowsRepoRoot: string;
|
||||
readonly allowBuild: boolean;
|
||||
}): Effect.fn.Return<
|
||||
WslPreflightSuccess | WslPreflightFailure,
|
||||
never,
|
||||
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
|
||||
> {
|
||||
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const wslAvailable = yield* wslEnv.isAvailable;
|
||||
if (!wslAvailable) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: "WSL is not available on this system",
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const distroProbe = yield* wslEnv.probeDistros.pipe(
|
||||
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
|
||||
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
|
||||
);
|
||||
if (distroProbe._tag === "Failure") {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const installedDistros = distroProbe.distros;
|
||||
const runningDistro = input.distro
|
||||
? (installedDistros.find(
|
||||
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
|
||||
)?.name ?? null)
|
||||
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
|
||||
if (runningDistro === null) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: input.distro
|
||||
? `WSL distro is not installed: ${input.distro}`
|
||||
: installedDistros.length === 0
|
||||
? "WSL has no installed distributions"
|
||||
: "WSL has no default distribution",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(input.windowsEntryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!entryExists) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `missing server entry at ${input.windowsEntryPath}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
|
||||
if (Option.isNone(linuxEntry)) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
|
||||
allowBuild: input.allowBuild,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
});
|
||||
if (!nodePtyResult.ok) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
|
||||
fatal: nodePtyResult.fatal,
|
||||
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
_tag: "Ready",
|
||||
runningDistro,
|
||||
linuxEntryPath: linuxEntry.value,
|
||||
nodePath: nodePtyResult.nodePath,
|
||||
resolvedPath: nodePtyResult.resolvedPath,
|
||||
} as const;
|
||||
});
|
||||
|
||||
// True when the given IPv4 belongs to a Windows-side network
|
||||
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
|
||||
// host's, which is the signature we use to detect that mode and
|
||||
// switch the renderer URL to loopback.
|
||||
const isLocalHostIpv4 = (ip: string): boolean => {
|
||||
const interfaces = NodeOS.networkInterfaces();
|
||||
for (const list of Object.values(interfaces)) {
|
||||
if (!list) continue;
|
||||
for (const entry of list) {
|
||||
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
|
||||
// the Node build Electron ships (41 / Node 22, verified), but some Node
|
||||
// builds report the numeric 4. Normalize to a string so a future runtime
|
||||
// bump can't silently break mirrored-mode detection and leave the
|
||||
// renderer pointed at the distro IP instead of loopback.
|
||||
const family = String(entry.family);
|
||||
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
|
||||
...Option.match(observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
});
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
@@ -92,70 +336,350 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
},
|
||||
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
|
||||
extendEnv: true,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "fd3",
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
};
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
},
|
||||
);
|
||||
|
||||
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
|
||||
input: SharedBootstrapInput & {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
|
||||
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
|
||||
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
|
||||
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
|
||||
// Windows. wslhost forwarding is unreliable on some Windows hosts:
|
||||
// the desktop's readiness probe and the renderer's saved-env-style
|
||||
// fetch both saw "Failed to fetch" when the backend only bound to
|
||||
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
|
||||
// WSL IP as the renderer-visible URL avoids that dependency.
|
||||
// Security-wise this is acceptable for the local-only WSL backend:
|
||||
// the network it exposes on is the WSL-vEthernet network, not the
|
||||
// LAN; the primary owns LAN exposure when the user opts in.
|
||||
const wslBindHost = "0.0.0.0";
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: input.port,
|
||||
// Omit t3Home so the Linux backend uses its own home dir instead of
|
||||
// the Windows-side baseDir (which would be a /mnt/c path and share
|
||||
// the SQLite file with the primary).
|
||||
host: wslBindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
// PortSchema rejects 0, so when tailscale serve is disabled we still
|
||||
// need a valid number in this slot. The backend reads tailscaleServePort
|
||||
// only when tailscaleServeEnabled is true, so the actual value here is
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
// In packaged builds environment.appRoot is .../resources/app.asar — an
|
||||
// archive FILE. The Windows primary reads its entry through
|
||||
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
|
||||
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
|
||||
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
|
||||
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
|
||||
// already a real directory, so this is a no-op.
|
||||
const wslAppRoot = environment.isPackaged
|
||||
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
|
||||
: environment.appRoot;
|
||||
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
|
||||
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
// changes between probing and spawning the backend.
|
||||
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
|
||||
const distroForConfig = runningDistro ?? input.distro;
|
||||
|
||||
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
|
||||
// reports a host interface, so use loopback instead; a failed probe also
|
||||
// falls back to loopback and preserves the previous behavior.
|
||||
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
|
||||
const usesSharedNetworkStack = Option.match(distroIp, {
|
||||
onNone: () => false,
|
||||
onSome: (ip) => isLocalHostIpv4(ip),
|
||||
});
|
||||
const rendererHost = usesSharedNetworkStack
|
||||
? "127.0.0.1"
|
||||
: Option.getOrElse(distroIp, () => "127.0.0.1");
|
||||
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
|
||||
|
||||
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
|
||||
const forwardedEnv: Record<string, string> = {};
|
||||
const forwardedEnvNames: string[] = [];
|
||||
for (const name of WSL_FORWARDED_ENV_NAMES) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined && value.length > 0) {
|
||||
forwardedEnv[name] = value;
|
||||
forwardedEnvNames.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
|
||||
// exports the Windows-side base dir for the primary; if it leaks into
|
||||
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
|
||||
// /mnt/c, which means both backends read/write the same database and
|
||||
// their env-ids collide).
|
||||
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "T3CODE_HOME") continue;
|
||||
parentEnvWithoutT3Home[key] = value;
|
||||
}
|
||||
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
|
||||
|
||||
const baseConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
entryPath: wslEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...parentEnvWithoutT3Home,
|
||||
...backendChildEnvPatch(),
|
||||
...forwardedEnv,
|
||||
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
|
||||
},
|
||||
// env is already a complete process.env minus T3CODE_HOME; pass it
|
||||
// verbatim instead of letting the spawner re-merge process.env on top.
|
||||
extendEnv: false,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "stdin" as const,
|
||||
httpBaseUrl,
|
||||
captureOutput: true,
|
||||
...(runningDistro !== null ? { runningDistro } : {}),
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
const devUrlArgs = Option.match(environment.devServerUrl, {
|
||||
onNone: () => [] as ReadonlyArray<string>,
|
||||
onSome: (url) => ["--dev-url", url.href],
|
||||
});
|
||||
|
||||
if (preflight._tag === "Failed") {
|
||||
const retryLimit =
|
||||
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [...distroArgs, "--", "node", "--version"],
|
||||
preflightFailure: Option.some({
|
||||
reason: preflight.reason,
|
||||
fatal: preflight.fatal,
|
||||
...(retryLimit === undefined ? {} : { retryLimit }),
|
||||
}),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
|
||||
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
|
||||
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
|
||||
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
|
||||
// user PATH entries captured by the login-shell preflight. Every dynamic
|
||||
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
|
||||
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
|
||||
// for the bootstrap envelope.
|
||||
const lastSlash = preflight.nodePath.lastIndexOf("/");
|
||||
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
|
||||
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
|
||||
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [
|
||||
...distroArgs,
|
||||
"--exec",
|
||||
"env",
|
||||
`PATH=${launchPath}`,
|
||||
preflight.nodePath,
|
||||
preflight.linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
...devUrlArgs,
|
||||
],
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
|
||||
// resolve concurrently; with a plain Ref both could observe None, generate
|
||||
// distinct tokens, and one would overwrite the other — leaving the two
|
||||
// backends holding mismatched tokens and breaking the shared-token
|
||||
// invariant the renderer relies on. modifyEffect serializes the whole
|
||||
// get-or-create so the first caller wins and the rest reuse its token.
|
||||
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
|
||||
Option.match(current, {
|
||||
onSome: (token) => Effect.succeed([token, current] as const),
|
||||
onNone: () =>
|
||||
crypto.randomBytes(24).pipe(
|
||||
Effect.map((bytes) => {
|
||||
const token = Encoding.encodeHex(bytes);
|
||||
return [token, Option.some(token)] as const;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
// Both resolvers share the same bootstrap token: the renderer holds a
|
||||
// single token and uses it against whichever backend it's currently
|
||||
// talking to. Observability settings get re-read each resolve so a
|
||||
// hot-swap of the server-settings file is picked up on the next
|
||||
// restart cycle without having to bounce the desktop process.
|
||||
const sharedInputs = Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
|
||||
});
|
||||
|
||||
const buildWslPrimaryConfig = Effect.gen(function* () {
|
||||
// wsl-only mode pipes the WSL backend through the same port the
|
||||
// Windows primary would normally take. That way the renderer
|
||||
// still loads from the local-only endpoint advertised by
|
||||
// DesktopServerExposure, and primary-aware code paths (cookie
|
||||
// auth, the env switcher's "primary" id) keep working without
|
||||
// a parallel "secondary" registration.
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
const persistedSettings = yield* settings.get;
|
||||
const shared = yield* sharedInputs;
|
||||
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
|
||||
return yield* resolveWslStartConfig({
|
||||
...shared,
|
||||
port: backendExposure.port,
|
||||
distro: persistedSettings.wslDistro,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
});
|
||||
|
||||
// Single source of truth for what the primary actually runs as. Both
|
||||
// the start-config dispatch and the renderer-facing label derive from
|
||||
// this, so they can't disagree — e.g. the label reading "WSL" while the
|
||||
// config silently fell back to Windows because WSL is unavailable.
|
||||
// Dispatch happens at resolve time so toggling wsl-only between restarts
|
||||
// is picked up on the next start cycle (the pool's primary instance is
|
||||
// created once at layer init, but configResolve fires on each restart).
|
||||
const describePrimary = Effect.gen(function* () {
|
||||
const persistedSettings = yield* settings.get;
|
||||
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
|
||||
// Only honor wsl-only when WSL is actually usable. If the user
|
||||
// persisted wsl-only but WSL has since become unavailable (wsl.exe
|
||||
// removed, no distro), fall back to the Windows primary instead of
|
||||
// looping forever on preflight failures: the Connections backend
|
||||
// control is hidden while WSL is unavailable, so a stuck WSL primary
|
||||
// would otherwise leave no in-app way back to Windows.
|
||||
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
|
||||
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resolvePrimary: Effect.gen(function* () {
|
||||
const { useWsl, wslRequested } = yield* describePrimary;
|
||||
if (useWsl) {
|
||||
return yield* buildWslPrimaryConfig;
|
||||
}
|
||||
if (wslRequested) {
|
||||
yield* Effect.logWarning(
|
||||
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
|
||||
);
|
||||
}
|
||||
return yield* buildWindowsPrimaryConfig;
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
|
||||
resolvePrimaryLabel: Effect.gen(function* () {
|
||||
const { useWsl, distro } = yield* describePrimary;
|
||||
if (!useWsl) {
|
||||
return environment.platform === "win32" ? "Windows" : "Local environment";
|
||||
}
|
||||
return distro ? `WSL (${distro})` : "WSL";
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
|
||||
resolveWsl: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
|
||||
attributes: { port: input.port, distro: input.distro ?? null },
|
||||
}),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
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.DesktopBackendOutputLog["Service"]),
|
||||
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.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
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())),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,11 +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 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";
|
||||
@@ -15,22 +39,25 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
// After this many consecutive fatal preflight failures, stop the silent
|
||||
// restart loop and surface the reason via onPreflightFailed. Transient
|
||||
// failures may instead provide their own larger retryLimit when they should
|
||||
// self-heal for a while but must not leave the app connecting forever.
|
||||
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
|
||||
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
@@ -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 {
|
||||
@@ -62,10 +112,10 @@ interface BackendProcessExit {
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.URL,
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
@@ -73,24 +123,24 @@ export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutE
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
|
||||
override get message() {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
executablePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend process: ${this.detail}`;
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,18 +165,60 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
// Opaque identifier for one backend process inside the pool. Today only
|
||||
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
|
||||
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
|
||||
// these map 1:1 with environment ids on the frontend; keeping them
|
||||
// desktop-local for now avoids leaking the contracts dependency.
|
||||
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
|
||||
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
);
|
||||
|
||||
// One pooled backend instance. Same lifecycle surface as the legacy
|
||||
// `DesktopBackendManagerShape`; the id and label give the pool registry
|
||||
// + UI something to route on.
|
||||
export interface DesktopBackendInstance {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
// Polls desiredRunning + the instance's own ready flag until the
|
||||
// backend reports ready, or the timeout elapses. Returns true on
|
||||
// ready, false on timeout. Used by the WSL backend swap to drive its
|
||||
// rollback path.
|
||||
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
// Spec describing one backend instance to spawn. The configResolve
|
||||
// effect is awaited each time the instance is (re)started so live
|
||||
// settings changes are picked up on the next start cycle. onReady and
|
||||
// onShutdown let the primary instance trigger UI side effects (window
|
||||
// open, global readiness flag) without coupling the factory to those
|
||||
// concerns; other instances pass them as undefined.
|
||||
export interface BackendInstanceSpec {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
// configResolve can now fail with PlatformError because the
|
||||
// bootstrap-token closure inside DesktopBackendConfiguration uses
|
||||
// crypto.randomBytes (Effect 4 beta.73 migration).
|
||||
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
|
||||
// Receives the *resolved* httpBaseUrl of the run that just became
|
||||
// ready. The window service uses this to decide what URL to load
|
||||
// (the WSL backend reports its distro IP, the Windows backend reports
|
||||
// 127.0.0.1). Splitting this off from configResolve avoids races
|
||||
// between "fired onReady" and "currentConfig already advanced".
|
||||
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
|
||||
readonly onShutdown?: () => Effect.Effect<void>;
|
||||
// Fired once when a fatal or bounded preflight failure has exhausted its
|
||||
// retries. Returns true when the callback changed configuration and the
|
||||
// manager should resolve once more; false stops the failed instance.
|
||||
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
interface ActiveBackendRun {
|
||||
readonly id: number;
|
||||
@@ -141,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;
|
||||
}
|
||||
@@ -151,6 +246,7 @@ const initialState: BackendManagerState = {
|
||||
config: Option.none(),
|
||||
active: Option.none(),
|
||||
restartAttempt: 0,
|
||||
preflightFailureAttempt: 0,
|
||||
restartFiber: Option.none(),
|
||||
nextRunId: 1,
|
||||
};
|
||||
@@ -183,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>,
|
||||
@@ -238,46 +331,37 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: true,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: options.extendEnv,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
@@ -296,18 +380,34 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
// its own state Ref, mutex, restart loop, and active child process;
|
||||
// nothing is shared between instances created from separate
|
||||
// makeBackendInstance calls. The instance shuts down automatically when
|
||||
// the calling scope closes (typically the application scope).
|
||||
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
spec: BackendInstanceSpec,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendInstance,
|
||||
never,
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| Scope.Scope
|
||||
> {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const { logWarning: logInstanceWarning, logError: logInstanceError } =
|
||||
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
|
||||
|
||||
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
|
||||
Ref.update(state, withActiveRun(runId, f));
|
||||
|
||||
@@ -347,10 +447,15 @@ export const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
if (current.ready) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.ready ? { ...latest, ready: false } : latest,
|
||||
);
|
||||
}
|
||||
const config = yield* spec.configResolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
logInstanceError("failed to generate desktop backend configuration", {
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
@@ -363,14 +468,84 @@ export const make = Effect.gen(function* () {
|
||||
.exists(config.value.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const resetFatalPreflightCounter =
|
||||
!current.desiredRunning && current.preflightFailureAttempt > 0;
|
||||
yield* cancelRestart;
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config.value),
|
||||
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
|
||||
}));
|
||||
|
||||
const preflightFailure = config.value.preflightFailure;
|
||||
if (Option.isSome(preflightFailure)) {
|
||||
const { reason, fatal, retryLimit } = preflightFailure.value;
|
||||
if (!fatal && retryLimit === undefined) {
|
||||
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
|
||||
// retrying so the backend self-heals once WSL is ready. Reset a
|
||||
// prior bounded/fatal streak because this is a different failure.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0
|
||||
? latest
|
||||
: { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
|
||||
const attempt = yield* Ref.modify(state, (latest) => {
|
||||
const next = latest.preflightFailureAttempt + 1;
|
||||
return [next, { ...latest, preflightFailureAttempt: next }] as const;
|
||||
});
|
||||
if (attempt > attemptLimit) {
|
||||
// We already surfaced and asked for the Windows fallback, yet we're
|
||||
// still resolving the WSL primary — the fallback didn't take (e.g.
|
||||
// the settings write failed). Stop rather than loop forever.
|
||||
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
|
||||
reason,
|
||||
attempt,
|
||||
});
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (attempt === attemptLimit) {
|
||||
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
|
||||
// on the primary, shows a dialog and persists Windows mode), then
|
||||
// schedule one more restart so the next resolve picks up the Windows
|
||||
// primary and a window can open.
|
||||
yield* logInstanceError(
|
||||
"backend preflight failed repeatedly; surfacing and falling back",
|
||||
{ reason, attempt },
|
||||
);
|
||||
const shouldRestart = yield* (
|
||||
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
|
||||
);
|
||||
if (shouldRestart) {
|
||||
yield* scheduleRestart(reason);
|
||||
} else {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
// Clean preflight — reset the fatal counter so a later failure gets a
|
||||
// fresh allowance.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
return;
|
||||
@@ -391,7 +566,7 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
]);
|
||||
|
||||
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
|
||||
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
@@ -443,7 +618,7 @@ export const make = Effect.gen(function* () {
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -455,7 +630,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
@@ -465,7 +640,7 @@ export const make = Effect.gen(function* () {
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
if (activeRun?.id !== runId) {
|
||||
@@ -485,17 +660,10 @@ export const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, true);
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
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),
|
||||
@@ -517,9 +685,9 @@ export const make = Effect.gen(function* () {
|
||||
}));
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.withSpan("desktop.backendManager.start"));
|
||||
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
|
||||
|
||||
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
|
||||
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
const scheduled = yield* Ref.modify(state, (latest) => {
|
||||
@@ -539,8 +707,8 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
yield* Option.match(scheduled, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
|
||||
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
});
|
||||
@@ -560,7 +728,7 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
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),
|
||||
}),
|
||||
),
|
||||
@@ -579,7 +747,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
@@ -597,7 +765,15 @@ export const make = Effect.gen(function* () {
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
// Ignore failures from spec.onShutdown so a downstream throw
|
||||
// can't abort the rest of stop(). Ref.modify above already
|
||||
// flipped state to "no active run / no restart fiber", and the
|
||||
// physical cleanup (Fiber.interrupt + closeRun) runs after the
|
||||
// mutex releases. If onShutdown were allowed to propagate, both
|
||||
// would be skipped and the child process + restart fiber would
|
||||
// be orphaned while state claimed nothing was running — the
|
||||
// next start() would then spawn a second backend on top.
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
@@ -612,14 +788,32 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
// Return false early if an external `stop()` flipped desiredRunning off
|
||||
// — no point polling for a backend that is being torn down.
|
||||
if (!current.desiredRunning) return { done: true, ready: false };
|
||||
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
|
||||
}).pipe(
|
||||
Effect.repeat({
|
||||
until: (status) => status.done,
|
||||
schedule: Schedule.spaced(Duration.millis(100)),
|
||||
}),
|
||||
Effect.map((status) => status.ready),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse(() => false)),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => stop());
|
||||
|
||||
return DesktopBackendManager.of({
|
||||
return {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
start,
|
||||
stop,
|
||||
currentConfig,
|
||||
snapshot,
|
||||
});
|
||||
waitForReady,
|
||||
} satisfies DesktopBackendInstance;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
@@ -0,0 +1,138 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
|
||||
|
||||
function makeStubInstance(
|
||||
id: DesktopBackendPool.BackendInstanceId,
|
||||
label: string,
|
||||
): DesktopBackendPool.DesktopBackendInstance {
|
||||
const snapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
label: Effect.succeed(label),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
function makePoolLayer(
|
||||
labelRef: Ref.Ref<string>,
|
||||
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
|
||||
return DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
FileSystem.layerNoop({}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
|
||||
),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
|
||||
DesktopAppSettings.layerTest(),
|
||||
ElectronDialog.layer,
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected window create"),
|
||||
ensureMain: Effect.die("unexpected window ensure"),
|
||||
revealOrCreateMain: Effect.die("unexpected window reveal"),
|
||||
activate: Effect.die("unexpected window activate"),
|
||||
createMainIfBackendReady: Effect.die("unexpected window create"),
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("DesktopBackendPool", () => {
|
||||
it.effect("layerTest exposes registered instances by id", () =>
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
|
||||
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
|
||||
const all = yield* pool.list;
|
||||
const resolvedPrimary = yield* pool.primary;
|
||||
|
||||
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
|
||||
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
|
||||
assert.isTrue(Option.isNone(fetchedMissing));
|
||||
assert.lengthOf(all, 2);
|
||||
// First instance becomes primary in layerTest so single-instance
|
||||
// stubs don't have to wire an explicit primary.
|
||||
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendPool.layerTest([
|
||||
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
|
||||
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("layerTest dies when no instances are supplied", () =>
|
||||
Effect.exit(
|
||||
Effect.gen(function* () {
|
||||
yield* DesktopBackendPool.DesktopBackendPool;
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
|
||||
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
|
||||
);
|
||||
|
||||
it.effect("resolves the primary label lazily after pool layer construction", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const labelRef = yield* Ref.make("Windows");
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
|
||||
Effect.provide(makePoolLayer(labelRef)),
|
||||
);
|
||||
const primary = yield* pool.primary;
|
||||
|
||||
yield* Ref.set(labelRef, "WSL (Ubuntu)");
|
||||
|
||||
assert.equal(yield* primary.label, "WSL (Ubuntu)");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,470 @@
|
||||
// Pool registry for multiple backend processes. This file is the entry
|
||||
// point for the concurrent-Windows+WSL-backend feature; see the design
|
||||
// notes below before extending it.
|
||||
//
|
||||
// Current state:
|
||||
// - `DesktopBackendManager.ts` exposes a per-instance factory
|
||||
// (`makeBackendInstance(spec)`); the pool calls it once for the
|
||||
// Windows primary at startup, and `DesktopWslBackend.reconcile`
|
||||
// calls it through `pool.register` to bring up the WSL instance
|
||||
// when the user enables it.
|
||||
// - The primary spec wires `configResolve` to
|
||||
// `DesktopBackendConfiguration.resolvePrimary` and the
|
||||
// `onReady`/`onShutdown` callbacks to the window service. WSL
|
||||
// instances wire `configResolve: configuration.resolveWsl(...)`
|
||||
// and skip onReady/onShutdown — the window only follows the primary.
|
||||
// - The pool exposes `register(spec)` and `unregister(id)`. Each
|
||||
// registered instance gets its own child scope, so unregister can
|
||||
// stop it cleanly without tearing down the pool. The primary's id
|
||||
// refuses unregister.
|
||||
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
|
||||
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
|
||||
// load. IPC surface is `setWslBackendEnabled(boolean)` +
|
||||
// `setWslDistro(string | null)`; both persist and then call the
|
||||
// orchestrator's reconcile. No swap, no rollback, primary stays up.
|
||||
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
|
||||
// pool instance currently registered with bootstrap info. The
|
||||
// primary keeps the "primary" id; WSL instances are "wsl:default"
|
||||
// or "wsl:<distro>".
|
||||
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
|
||||
// it gives the Windows picker — what every existing caller gets,
|
||||
// and what non-WSL users see. WSL targets route to the wsl helpers.
|
||||
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
|
||||
// picker that shows up when the toggle is on. Default-off, so
|
||||
// users who never opted in see the same surface as before.
|
||||
//
|
||||
// Renderer-side wiring (apps/web/src/environments/local/):
|
||||
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
|
||||
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
|
||||
// skips the primary (which the existing primary/ runtime owns),
|
||||
// and for every other entry POSTs the shared bootstrap token to
|
||||
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
|
||||
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
|
||||
// writes the bearer to the secret store, and opens a connection
|
||||
// through the same saved-env path remote envs use.
|
||||
// - The desktopLocal marker filters records out of saved-env
|
||||
// persistence, so toggling WSL off or switching distros doesn't
|
||||
// pollute the user's settings file. The sidebar, CommandPalette,
|
||||
// env switcher, and project-id routing all read the saved-env
|
||||
// registry, so the WSL backend shows up there without any
|
||||
// per-surface changes.
|
||||
//
|
||||
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
|
||||
// wslDistro="Ubuntu"):
|
||||
// - Two backends listening on distinct loopback ports
|
||||
// (server.log: 13773 primary, 13774 wsl).
|
||||
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
|
||||
// - Distinct environment ids reported by each backend's
|
||||
// /.well-known/t3/environment (Windows vs Linux platform).
|
||||
// - Renderer completes the bearer-token bootstrap against the WSL
|
||||
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
|
||||
// ws-token (POST /api/auth/ws-token 200), and holds an
|
||||
// ESTABLISHED WebSocket connection to both ports (netstat).
|
||||
//
|
||||
// Migration history (commits):
|
||||
// 1. Reshape `DesktopBackendManager` into an instance factory and route
|
||||
// consumers through the pool. Pool held a single instance. (a8fc7845)
|
||||
// 2. Drop `DesktopState.backendReady`. The window owns its own
|
||||
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
|
||||
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
|
||||
// 4. Add register/unregister to the pool. (a0eaf560)
|
||||
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
|
||||
// split, DesktopWslBackend orchestrator, new IPC, web compat.
|
||||
// (b1622191 + 31ce3add + 627c80cb)
|
||||
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
|
||||
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
|
||||
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
|
||||
// 9. Register WSL backend as desktop-local saved env via
|
||||
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
|
||||
// 10. CommandPalette enables file-manager picker for desktop-local
|
||||
// envs, routes pickFolder by env id. (38e8477a)
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
const { logWarning: logBackendPoolWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-pool");
|
||||
|
||||
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
|
||||
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
|
||||
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
|
||||
|
||||
// Caller tried to register an id that's already in the pool. The pool
|
||||
// refuses overwrites so two independent orchestrators racing on the
|
||||
// same id surface as a typed failure instead of one silently winning.
|
||||
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
|
||||
"DesktopBackendPoolInstanceAlreadyRegisteredError",
|
||||
{
|
||||
id: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Backend instance "${this.id}" is already registered in the pool.`;
|
||||
}
|
||||
}
|
||||
|
||||
// Primary instance is registered for the pool's lifetime. Unregister is
|
||||
// a no-op for it today (no real callers), but if someone wires it up
|
||||
// later it's a clear bug rather than something to "handle".
|
||||
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
|
||||
"DesktopBackendPoolCannotUnregisterPrimaryError",
|
||||
{},
|
||||
) {
|
||||
override get message() {
|
||||
return "Refusing to unregister the primary backend from the pool.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendPool extends Context.Service<
|
||||
DesktopBackendPool,
|
||||
{
|
||||
// Look up a registered instance. None when no backend with that id is
|
||||
// currently registered (e.g. WSL backend disabled).
|
||||
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
|
||||
// Snapshot of all currently-registered instances. Order is unspecified;
|
||||
// callers that need a canonical "primary first" view should sort by id.
|
||||
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
|
||||
// Convenience accessor for the always-registered primary instance.
|
||||
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
|
||||
// exposed as a typed effect so consumers don't have to handle the
|
||||
// Option for the case that's guaranteed to be present.
|
||||
readonly primary: Effect.Effect<DesktopBackendInstance>;
|
||||
// Build a fresh DesktopBackendInstance from `spec` and add it to the
|
||||
// registry. The pool owns the instance's scope: unregister(id) or pool
|
||||
// teardown closes it and runs the instance's auto-stop finalizer. The
|
||||
// returned instance has not been started — callers decide when to
|
||||
// start it (and can call start more than once if a retry-after-failure
|
||||
// story makes sense for them).
|
||||
readonly register: (
|
||||
spec: BackendInstanceSpec,
|
||||
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
|
||||
// Stop the named instance and remove it from the registry. Closing the
|
||||
// instance's scope triggers its auto-stop finalizer; the registry is
|
||||
// updated atomically with the scope close so subsequent get(id) calls
|
||||
// observe the unregister before the underlying child process has fully
|
||||
// exited.
|
||||
readonly unregister: (
|
||||
id: BackendInstanceId,
|
||||
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
|
||||
|
||||
// Services required by makeBackendInstance — exported so caller
|
||||
// orchestrators that build their own specs can confirm the layer graph
|
||||
// satisfies them at compile time.
|
||||
export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
readonly instance: DesktopBackendInstance;
|
||||
// None for the primary (which lives in the pool's own layer scope and
|
||||
// is never unregistered); Some for instances added via register, whose
|
||||
// scope unregister closes to stop them.
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
interface ClosingRegisteredInstance {
|
||||
readonly _tag: "Closing";
|
||||
readonly done: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
|
||||
|
||||
type RegisterAction =
|
||||
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
|
||||
|
||||
type UnregisterAction =
|
||||
| { readonly _tag: "Absent" }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
|
||||
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
// Anchor the pool's lifetime to its layer scope so registered
|
||||
// instance scopes can be forked off it. Without this, instance
|
||||
// scopes are orphaned: they only close via explicit unregister()
|
||||
// calls, so on app shutdown the WSL backend child process gets
|
||||
// hard-killed by the OS instead of receiving the graceful
|
||||
// SIGTERM + grace period the instance's stop finalizer would
|
||||
// otherwise run.
|
||||
const layerScope = yield* Scope.Scope;
|
||||
// Capture the services needed to build any future instance from the
|
||||
// pool's layer scope. register() runs `makeBackendInstance` against
|
||||
// a fresh child scope but reuses these services so the instance gets
|
||||
// the same FileSystem, spawner, HTTP client and log factory the
|
||||
// primary instance uses.
|
||||
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
|
||||
|
||||
// A WSL preflight failure on the primary only happens in wsl-only mode.
|
||||
// Fatal configuration failures persist the Windows fallback. Bounded
|
||||
// transport failures use an in-memory fallback for this launch so the app
|
||||
// opens without overwriting the user's WSL preference.
|
||||
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
|
||||
function* (failure: DesktopBackendManager.PreflightFailure) {
|
||||
const { reason, fatal } = failure;
|
||||
if (!fatal) {
|
||||
yield* logBackendPoolWarning(
|
||||
"primary WSL preflight retry window exhausted; using Windows for this launch",
|
||||
{ reason },
|
||||
);
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend is still unavailable",
|
||||
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
|
||||
);
|
||||
yield* appSettings.applyWslWindowsFallbackInMemory;
|
||||
return true;
|
||||
}
|
||||
|
||||
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
|
||||
reason,
|
||||
});
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend couldn't start",
|
||||
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
|
||||
);
|
||||
// Fully disable the WSL backend — both flags, matching the "Switch to
|
||||
// Windows" recovery path — so the manager's next restart re-resolves the
|
||||
// primary as Windows and reconcile won't register a secondary WSL backend
|
||||
// against the same broken setup. Clearing wslBackendEnabled alone would
|
||||
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
|
||||
// mode the next time they enable WSL. If the persisted write fails, keep
|
||||
// this process recoverable by applying the fallback to in-memory settings.
|
||||
yield* appSettings.applyWslWindowsFallback.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning(
|
||||
"failed to persist Windows fallback after WSL preflight failure",
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const primary = yield* DesktopBackendManager.makeBackendInstance({
|
||||
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
// Keep this lazy. The pool layer is initialized before startup loads
|
||||
// persisted desktop settings, so resolving the primary label here would
|
||||
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
|
||||
// primaries as Windows.
|
||||
label: configuration.resolvePrimaryLabel,
|
||||
configResolve: configuration.resolvePrimary,
|
||||
// Window creation errors propagating out of handleBackendReady must
|
||||
// not block the readiness callback (that would prevent restartAttempt
|
||||
// from being reset), so we absorb them here. The window service only
|
||||
// logs on success, so log the failure here before swallowing it —
|
||||
// otherwise a post-readiness window-open failure vanishes silently and
|
||||
// is near-impossible to diagnose in production.
|
||||
onReady: (httpBaseUrl) =>
|
||||
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning("failed to open main window after backend readiness", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
onShutdown: () => desktopWindow.handleBackendNotReady,
|
||||
onPreflightFailed: handlePrimaryPreflightFailure,
|
||||
});
|
||||
|
||||
const instancesRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<BackendInstanceId, RegisteredInstance>
|
||||
>(
|
||||
new Map([
|
||||
[
|
||||
DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
{ _tag: "Active", instance: primary, scope: Option.none() },
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
|
||||
Effect.suspend(() =>
|
||||
SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
|
||||
DesktopBackendPoolInstanceAlreadyRegisteredError
|
||||
> => {
|
||||
const existing = current.get(spec.id);
|
||||
if (existing?._tag === "Active") {
|
||||
return Effect.fail(
|
||||
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
|
||||
);
|
||||
}
|
||||
if (existing?._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: existing.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
// Provide the captured factory services first, then the child scope
|
||||
// last so instance finalizers are owned by the unregisterable scope.
|
||||
const instanceScope = yield* Scope.fork(layerScope, "sequential");
|
||||
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
|
||||
Effect.provide(factoryContext),
|
||||
Scope.provide(instanceScope),
|
||||
);
|
||||
const next = new Map(current);
|
||||
next.set(spec.id, {
|
||||
_tag: "Active",
|
||||
instance,
|
||||
scope: Option.some(instanceScope),
|
||||
});
|
||||
return [
|
||||
{ _tag: "Registered", instance } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const;
|
||||
});
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result._tag === "Registered"
|
||||
? Effect.succeed(result.instance)
|
||||
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
|
||||
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
|
||||
}
|
||||
const done = yield* Deferred.make<void>();
|
||||
const action = yield* SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
|
||||
> => {
|
||||
const entry = current.get(id);
|
||||
if (entry === undefined) {
|
||||
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
|
||||
}
|
||||
if (entry._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: entry.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(id, { _tag: "Closing", done });
|
||||
return Effect.succeed([
|
||||
{ _tag: "Close", entry } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
},
|
||||
);
|
||||
|
||||
if (action._tag === "Absent") return;
|
||||
if (action._tag === "Wait") {
|
||||
yield* Deferred.await(action.done);
|
||||
return;
|
||||
}
|
||||
|
||||
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
|
||||
const closing = current.get(id);
|
||||
if (closing?._tag !== "Closing" || closing.done !== done) {
|
||||
return Effect.succeed([undefined, current] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(id);
|
||||
return Effect.succeed([
|
||||
undefined,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
|
||||
yield* Option.match(action.entry.scope, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
|
||||
}).pipe(Effect.ensuring(finish));
|
||||
});
|
||||
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) =>
|
||||
SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) => {
|
||||
const entry = instances.get(id);
|
||||
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
|
||||
}),
|
||||
),
|
||||
list: SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) =>
|
||||
Array.from(instances.values()).flatMap((entry) =>
|
||||
entry._tag === "Active" ? [entry.instance] : [],
|
||||
),
|
||||
),
|
||||
),
|
||||
primary: Effect.succeed(primary),
|
||||
register,
|
||||
unregister,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Test layer for unit tests that want to assert against a known pool
|
||||
// composition without standing up the full manager. Each provided
|
||||
// instance is registered under its own id; the first one is also
|
||||
// surfaced as `primary` so callers can stub a single-instance pool.
|
||||
// `register` and `unregister` are stubbed to die so tests that
|
||||
// accidentally exercise pool registration fail loudly instead of
|
||||
// silently noop'ing.
|
||||
export const layerTest = (
|
||||
instances: readonly DesktopBackendInstance[],
|
||||
): Layer.Layer<DesktopBackendPool> =>
|
||||
Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
if (instances.length === 0) {
|
||||
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
|
||||
}
|
||||
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
|
||||
instances.map((instance) => [instance.id, instance] as const),
|
||||
);
|
||||
const primary = instances[0]!;
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
|
||||
list: Effect.succeed(Array.from(byId.values())),
|
||||
primary: Effect.succeed(primary),
|
||||
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
|
||||
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -5,11 +5,12 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
const config = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
@@ -54,20 +55,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
});
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
list: Effect.succeed([
|
||||
{
|
||||
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
},
|
||||
]),
|
||||
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
|
||||
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -8,7 +9,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
@@ -42,7 +43,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
@@ -55,14 +56,20 @@ export const make = Effect.gen(function* () {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
const instances = yield* pool.list;
|
||||
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
|
||||
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const credential = config.bootstrap.desktopBootstrapToken;
|
||||
if (!credential) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
credential,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
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;
|
||||
@@ -18,6 +20,18 @@ 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,
|
||||
{
|
||||
@@ -25,9 +39,14 @@ export class DesktopNetworkInterfaces extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = (): DesktopNetworkInterfaces["Service"] =>
|
||||
DesktopNetworkInterfaces.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
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.succeed(DesktopNetworkInterfaces, make());
|
||||
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
|
||||
@@ -91,6 +91,7 @@ function makeLayer(input: {
|
||||
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);
|
||||
@@ -99,7 +100,7 @@ function makeLayer(input: {
|
||||
});
|
||||
|
||||
return DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
@@ -122,6 +123,7 @@ const withHarness = <A, E, R>(
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -135,6 +137,7 @@ const withHarness = <A, E, R>(
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -237,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 },
|
||||
|
||||
@@ -2,11 +2,12 @@ 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";
|
||||
@@ -213,23 +214,45 @@ export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErr
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
|
||||
"DesktopServerExposureModePersistenceError",
|
||||
{
|
||||
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
|
||||
mode: DesktopServerExposureModeSchema,
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
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;
|
||||
@@ -258,7 +281,7 @@ export class DesktopServerExposure extends Context.Service<
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
@@ -449,8 +472,8 @@ export 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,
|
||||
}),
|
||||
),
|
||||
@@ -477,8 +500,9 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "tailscale-serve",
|
||||
new DesktopTailscaleServePersistenceError({
|
||||
enabled: input.enabled,
|
||||
port: input.port ?? null,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,12 +14,36 @@ export interface ElectronAppMetadata {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
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 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>;
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void>;
|
||||
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>;
|
||||
@@ -63,15 +88,40 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
export 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,
|
||||
})),
|
||||
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)),
|
||||
);
|
||||
});
|
||||
@@ -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>;
|
||||
@@ -22,17 +91,24 @@ export class ElectronDialog extends Context.Service<
|
||||
{
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue>;
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronDialog") {}
|
||||
|
||||
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"],
|
||||
@@ -42,10 +118,18 @@ export 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) {
|
||||
@@ -67,17 +151,48 @@ export 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);
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
|
||||
@@ -23,6 +24,28 @@ export interface ElectronMenuTemplateInput {
|
||||
readonly template: readonly Electron.MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
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,
|
||||
{
|
||||
@@ -71,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
// Renderer positions arrive in CSS pixels; popup() expects window points, so
|
||||
// page zoom must be factored in or menus drift proportionally to their
|
||||
// distance from the window origin.
|
||||
const normalizePosition = (
|
||||
position: Option.Option<ElectronMenuPosition>,
|
||||
zoomFactor: number,
|
||||
): Option.Option<ElectronMenuPosition> =>
|
||||
Option.filter(
|
||||
position,
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
({ x, y }) =>
|
||||
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
|
||||
).pipe(
|
||||
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
@@ -142,16 +172,36 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
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);
|
||||
@@ -169,21 +219,42 @@ export const make = Effect.gen(function* () {
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
|
||||
@@ -42,7 +43,16 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -69,6 +79,11 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -98,6 +113,88 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
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",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -31,7 +32,19 @@ export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<E
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register ${this.scheme}: protocol.`;
|
||||
return `Failed to register Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
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}".`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,18 +115,60 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
@@ -133,9 +188,14 @@ export const make = Effect.gen(function* () {
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unhandle(input.scheme);
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false))),
|
||||
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),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -1,16 +1,31 @@
|
||||
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 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 const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
|
||||
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronTheme") {}
|
||||
@@ -18,9 +33,11 @@ export class ElectronTheme extends Context.Service<
|
||||
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,16 +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.equal(error.message, "Electron updater failed to check for updates.");
|
||||
}
|
||||
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)),
|
||||
);
|
||||
});
|
||||
@@ -10,40 +10,41 @@ type AutoUpdater = typeof autoUpdater;
|
||||
|
||||
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
|
||||
|
||||
const electronUpdaterErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
|
||||
"ElectronUpdaterCheckForUpdatesError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron updater failed to check for updates.";
|
||||
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
|
||||
"ElectronUpdaterDownloadUpdateError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron updater failed to download the update.";
|
||||
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
|
||||
"ElectronUpdaterQuitAndInstallError",
|
||||
{
|
||||
...electronUpdaterErrorFields,
|
||||
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.";
|
||||
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +66,7 @@ export class ElectronUpdater extends Context.Service<
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
@@ -111,23 +113,43 @@ export const make = ElectronUpdater.of({
|
||||
autoUpdater.allowDowngrade = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.fullChangelog = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setDisableDifferentialDownload: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
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 {
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -8,14 +8,69 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
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 {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
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 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}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +98,38 @@ 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;
|
||||
@@ -53,27 +137,60 @@ export 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,
|
||||
@@ -89,45 +206,75 @@ export 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 (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);
|
||||
|
||||
@@ -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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -24,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>;
|
||||
@@ -39,10 +72,10 @@ export class DesktopIpc extends Context.Service<
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
|
||||
@@ -57,18 +90,27 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
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,18 +123,30 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
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),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -33,21 +33,24 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getLocalEnvironmentBootstrap,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
@@ -70,6 +73,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTailscaleServeEnabled);
|
||||
yield* ipc.handle(getAdvertisedEndpoints);
|
||||
|
||||
yield* ipc.handle(getWslState);
|
||||
yield* ipc.handle(setWslBackendEnabled);
|
||||
yield* ipc.handle(setWslDistro);
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
|
||||
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
@@ -11,7 +13,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
@@ -32,6 +34,10 @@ 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";
|
||||
|
||||
@@ -19,37 +19,30 @@ import {
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserWindow } from "electron";
|
||||
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";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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) => {
|
||||
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
});
|
||||
yield* manager.subscribeRecordingFrames((frame) => {
|
||||
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
});
|
||||
yield* manager.subscribePointerEvents((event) => {
|
||||
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
});
|
||||
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({
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
|
||||
entryPath: "/app/bin.mjs",
|
||||
cwd: "/app",
|
||||
env: {},
|
||||
extendEnv: false,
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3774,
|
||||
host: "0.0.0.0",
|
||||
desktopBootstrapToken: "bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
bootstrapDelivery: "stdin",
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3774"),
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
runningDistro: "Ubuntu",
|
||||
};
|
||||
|
||||
const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
id: DesktopBackendManager.BackendInstanceId("wsl:default"),
|
||||
label: Effect.succeed("WSL (default distro)"),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.some(readyWslConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: true,
|
||||
activePid: Option.some(123),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
|
||||
describe("getLocalEnvironmentBootstraps", () => {
|
||||
it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (Ubuntu)",
|
||||
runningDistro: "Ubuntu",
|
||||
httpBaseUrl: "http://127.0.0.1:3774/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3774/",
|
||||
bootstrapToken: "bootstrap-token",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
|
||||
);
|
||||
|
||||
it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
|
||||
const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
};
|
||||
const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(Option.some(retryingConfig)),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 2,
|
||||
restartScheduled: true,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, [
|
||||
{
|
||||
id: "wsl:default",
|
||||
label: "WSL (default distro)",
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
|
||||
});
|
||||
|
||||
it.effect("omits a bounded transient bootstrap after retries stop", () => {
|
||||
const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
|
||||
...defaultWslInstance,
|
||||
currentConfig: Effect.succeed(
|
||||
Option.some({
|
||||
...readyWslConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 12,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 12,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* getLocalEnvironmentBootstraps.handler();
|
||||
assert.deepEqual(result, []);
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getWindowFullscreenState", () => {
|
||||
it.effect("reads the current native window state", () => {
|
||||
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
assert.isTrue(yield* getWindowFullscreenState.handler());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(ElectronWindow.ElectronWindow)({
|
||||
currentMainOrFirst: Effect.succeed(Option.some(window)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,14 +4,19 @@ import {
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
@@ -19,6 +24,11 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
import {
|
||||
extractDistroFromUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
wslUncPathToLinuxPath,
|
||||
} from "../../wsl/wslPathParsing.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -45,26 +55,89 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
|
||||
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const config = yield* backendManager.currentConfig;
|
||||
return Option.match(config, {
|
||||
onNone: () => null,
|
||||
onSome: ({ bootstrap, httpBaseUrl }) => ({
|
||||
label: "Local environment",
|
||||
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const window = yield* electronWindow.currentMainOrFirst;
|
||||
return Option.isSome(window) && window.value.isFullScreen();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const instances = yield* pool.list;
|
||||
const bootstraps: DesktopEnvironmentBootstrap[] = [];
|
||||
for (const instance of instances) {
|
||||
const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
const config = yield* instance.currentConfig;
|
||||
const snapshot = yield* instance.snapshot;
|
||||
// A secondary backend (e.g. a parallel WSL backend) that hasn't produced
|
||||
// a config yet (mid-registration, before its first start cycle) or that
|
||||
// is retrying a *transient* preflight failure (WSL VM still booting, a
|
||||
// not-yet-built linux server entry) is not listening on a port. We
|
||||
// surface it as a *pending* bootstrap (null endpoints, no token) so the
|
||||
// renderer can show a "Connecting…" indicator while it retries — null
|
||||
// endpoints keep the renderer from dialing the dead port, avoiding the
|
||||
// needless /api/auth/bootstrap/bearer error cycles a real endpoint would
|
||||
// trigger.
|
||||
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
|
||||
// Skip the primary (same-origin, no "connecting" affordance) and skip a
|
||||
// secondary whose preflight failed *fatally* (no node, wrong version,
|
||||
// missing build tools): it has stopped retrying, so an indefinite
|
||||
// "Connecting…" would be misleading — its error is surfaced by the
|
||||
// WSL-state UI instead.
|
||||
const fatalPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
config.value.preflightFailure.value.fatal;
|
||||
const stoppedPreflight =
|
||||
Option.isSome(config) &&
|
||||
Option.isSome(config.value.preflightFailure) &&
|
||||
(!snapshot.desiredRunning || !snapshot.restartScheduled);
|
||||
if (isPrimary || fatalPreflight || stoppedPreflight) continue;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: yield* instance.label,
|
||||
runningDistro: null,
|
||||
httpBaseUrl: null,
|
||||
wsBaseUrl: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const { bootstrap, httpBaseUrl } = config.value;
|
||||
const runningDistro = config.value.runningDistro ?? null;
|
||||
bootstraps.push({
|
||||
id: instance.id,
|
||||
label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
|
||||
runningDistro,
|
||||
httpBaseUrl: httpBaseUrl.href,
|
||||
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
|
||||
...(bootstrap.desktopBootstrapToken
|
||||
? { bootstrapToken: bootstrap.desktopBootstrapToken }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
return bootstraps;
|
||||
}),
|
||||
});
|
||||
|
||||
// Pull the distro selection out of a backend instance id like
|
||||
// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
|
||||
// for "track the user's WSL default distro" and maps to the
|
||||
// wslEnv-derived default at picker time.
|
||||
function extractWslDistroFromEnvironmentId(envId: string): string | null {
|
||||
if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
|
||||
return suffix === "default" || suffix.length === 0 ? null : suffix;
|
||||
}
|
||||
|
||||
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
@@ -83,11 +156,62 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
// Three picker modes:
|
||||
// - targetEnvironmentId omitted: default to the primary picker. Keeps
|
||||
// the historical behavior unchanged for users who never enabled the
|
||||
// WSL backend, and is what unfamiliar callers should get out of the
|
||||
// box.
|
||||
// - targetEnvironmentId starts with "wsl:": route to the WSL picker
|
||||
// using the distro encoded in the id (or the user's selected
|
||||
// wslDistro when the id is the "wsl:default" sentinel).
|
||||
// - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
|
||||
const targetId = options?.targetEnvironmentId;
|
||||
const wslDistroFromTarget =
|
||||
targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
|
||||
? extractWslDistroFromEnvironmentId(targetId)
|
||||
: null;
|
||||
const useWsl =
|
||||
targetId !== undefined &&
|
||||
targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
|
||||
targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
|
||||
const settings = yield* appSettings.get;
|
||||
// Fall back to the persisted wslDistro when the id is the
|
||||
// "wsl:default" sentinel; the orchestrator uses the same fallback
|
||||
// for the actual backend.
|
||||
const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
|
||||
const defaultPath = useWsl
|
||||
? Option.fromNullishOr(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
options,
|
||||
{ distro: wslDistro },
|
||||
yield* wslEnvironment.listDistros,
|
||||
Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
|
||||
),
|
||||
)
|
||||
: environment.resolvePickFolderDefaultPath(options);
|
||||
const selectedPath = yield* dialog.pickFolder({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath: environment.resolvePickFolderDefaultPath(options),
|
||||
defaultPath,
|
||||
});
|
||||
return Option.getOrNull(selectedPath);
|
||||
if (Option.isNone(selectedPath)) {
|
||||
return null;
|
||||
}
|
||||
if (!useWsl) {
|
||||
return selectedPath.value;
|
||||
}
|
||||
|
||||
const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
|
||||
if (linuxUncPath !== null) {
|
||||
return linuxUncPath;
|
||||
}
|
||||
|
||||
const converted = yield* wslEnvironment.windowsToWslPath(
|
||||
extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
|
||||
selectedPath.value,
|
||||
);
|
||||
return Option.getOrElse(converted, () => selectedPath.value);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import { DesktopWslStateSchema } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
|
||||
import * as DesktopState from "../../app/DesktopState.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../../window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
|
||||
|
||||
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
|
||||
|
||||
const invokeSetWslBackendEnabled = (enabled: boolean) =>
|
||||
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslDistro = (distro: string | null) =>
|
||||
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
|
||||
const invokeSetWslOnly = (enabled: boolean) =>
|
||||
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
|
||||
|
||||
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
|
||||
return Layer.succeed(
|
||||
DesktopWslBackend.DesktopWslBackend,
|
||||
DesktopWslBackend.DesktopWslBackend.of({
|
||||
reconcile: input.onReconcile ?? Effect.void,
|
||||
lastPreflightError: Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeLifecycleLayer(relaunchReasons: Array<string>) {
|
||||
return Layer.succeed(
|
||||
DesktopLifecycle.DesktopLifecycle,
|
||||
DesktopLifecycle.DesktopLifecycle.of({
|
||||
relaunch: (reason) =>
|
||||
Effect.sync(() => {
|
||||
relaunchReasons.push(reason);
|
||||
}),
|
||||
register: Effect.void,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
|
||||
DesktopShutdown.layer,
|
||||
DesktopState.layer,
|
||||
Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of(
|
||||
{} as DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
),
|
||||
),
|
||||
Layer.succeed(
|
||||
DesktopWindow.DesktopWindow,
|
||||
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronApp.ElectronApp,
|
||||
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronTheme.ElectronTheme,
|
||||
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
|
||||
),
|
||||
);
|
||||
|
||||
describe("WSL IPC", () => {
|
||||
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* invokeSetWslOnly(false);
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer(),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const stagedMode = yield* invokeSetWslOnly(true);
|
||||
assert.equal(stagedMode.enabled, false);
|
||||
assert.equal(stagedMode.wslOnly, true);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
yield* invokeSetWslDistro("Debian");
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: "Debian",
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: true,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: true,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("reconciles in dual-backend mode without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(true);
|
||||
|
||||
assert.equal(state.enabled, true);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
|
||||
assert.deepEqual(state, {
|
||||
enabled: false,
|
||||
distro: null,
|
||||
available: true,
|
||||
wslOnly: false,
|
||||
distros: [],
|
||||
preflightError: null,
|
||||
});
|
||||
assert.equal(settings.wslBackendEnabled, false);
|
||||
assert.equal(settings.wslOnly, false);
|
||||
assert.equal(reconcileCount, 0);
|
||||
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("clears dual-backend WSL without relaunching", () => {
|
||||
const relaunchReasons: Array<string> = [];
|
||||
let reconcileCount = 0;
|
||||
const layer = Layer.mergeAll(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: false,
|
||||
}),
|
||||
DesktopWslEnvironment.layerTest({ isAvailable: true }),
|
||||
makeWslBackendLayer({
|
||||
onReconcile: Effect.sync(() => {
|
||||
reconcileCount += 1;
|
||||
}),
|
||||
}),
|
||||
makeLifecycleLayer(relaunchReasons),
|
||||
unusedLifecycleRuntimeLayer,
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const state = yield* invokeSetWslBackendEnabled(false);
|
||||
|
||||
assert.equal(state.enabled, false);
|
||||
assert.equal(state.wslOnly, false);
|
||||
assert.equal(reconcileCount, 1);
|
||||
assert.deepEqual(relaunchReasons, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const readWslState: Effect.Effect<
|
||||
DesktopWslState,
|
||||
never,
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| DesktopWslBackend.DesktopWslBackend
|
||||
> = Effect.gen(function* () {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
// Only enumerate distros when WSL is actually available — listDistros on a
|
||||
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
|
||||
const distros = available ? yield* wslEnvironment.listDistros : [];
|
||||
const preflightError = yield* wslBackend.lastPreflightError;
|
||||
return {
|
||||
enabled: settings.wslBackendEnabled,
|
||||
distro: settings.wslDistro,
|
||||
available,
|
||||
wslOnly: settings.wslOnly,
|
||||
distros,
|
||||
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
|
||||
// a dialog + Windows fallback, so it stays null there.
|
||||
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
|
||||
};
|
||||
});
|
||||
|
||||
export const getWslState = makeIpcMethod({
|
||||
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslBackendEnabled = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const previousSettings = yield* appSettings.get;
|
||||
const updateSettings = enabled
|
||||
? appSettings.setWslBackendEnabled(true)
|
||||
: appSettings.applyWslWindowsFallback;
|
||||
const change = yield* updateSettings;
|
||||
const settings = yield* appSettings.get;
|
||||
const changedWslOnlyPrimary = enabled
|
||||
? settings.wslOnly
|
||||
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
|
||||
if (changedWslOnlyPrimary && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
|
||||
return state;
|
||||
}
|
||||
// Reconcile is idempotent and never fails; no need for a swap-style
|
||||
// rollback when the WSL side has trouble coming up. With both
|
||||
// backends running side by side, "WSL didn't start" is a transient
|
||||
// state on one instance — the primary stays up either way.
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslDistro = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
|
||||
payload: Schema.NullOr(Schema.String),
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslDistro(distro);
|
||||
const settings = yield* appSettings.get;
|
||||
// In active wsl-only mode the pool's primary IS the WSL backend, and its
|
||||
// distro is captured when that backend starts, so relaunch to replace it.
|
||||
// When WSL is disabled, this only stages a preference for the next enable.
|
||||
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
|
||||
const state = yield* readWslState;
|
||||
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
|
||||
return state;
|
||||
}
|
||||
yield* wslBackend.reconcile;
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslOnly = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
|
||||
payload: Schema.Boolean,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
|
||||
// wsl-only decides which backend the pool spins up as "primary", and that
|
||||
// decision is captured once at layer init. A disabled WSL backend always
|
||||
// leaves Windows primary active, so mode changes can be staged without a
|
||||
// relaunch and applied by the subsequent enable call.
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const change = yield* appSettings.setWslOnly(enabled);
|
||||
const state = yield* readWslState;
|
||||
if (state.enabled && change.changed) {
|
||||
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
|
||||
}
|
||||
return state;
|
||||
}),
|
||||
});
|
||||
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
@@ -50,6 +50,8 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -143,12 +145,25 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
Layer.provideMerge(desktopPreviewLayer),
|
||||
);
|
||||
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
// Pool layer instantiates the backend factory once for the Windows
|
||||
// primary instance and exposes it via pool.primary. Consumers go through
|
||||
// the pool now; the legacy DesktopBackendManager service is gone. The
|
||||
// WSL second instance gets registered later in the migration. See
|
||||
// DesktopBackendPool.ts header for the full rollout plan.
|
||||
const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
// WSL orchestrator hangs off the backend layer because it needs the
|
||||
// pool + configuration + serverExposure; it pulls NetService and the
|
||||
// foundation services through the same provideMerge chain.
|
||||
const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
@@ -160,6 +175,7 @@ const desktopApplicationLayer = Layer.mergeAll(
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopWslBackendLayer),
|
||||
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
getLocalEnvironmentBootstraps: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
|
||||
if (!Array.isArray(result)) {
|
||||
return [];
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
|
||||
},
|
||||
getLocalEnvironmentBearerToken: () =>
|
||||
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
|
||||
@@ -91,6 +91,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
@@ -111,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
|
||||
if (typeof fullscreen !== "boolean") return;
|
||||
listener(fullscreen);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) =>
|
||||
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
@@ -13,6 +15,7 @@ const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
readonly clearStorageData: ReturnType<typeof vi.fn>;
|
||||
readonly getUserAgent: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
|
||||
readonly setUserAgent: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
>(),
|
||||
@@ -38,6 +41,7 @@ describe("BrowserSession", () => {
|
||||
clearStorageData: vi.fn(() => Promise.resolve()),
|
||||
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
|
||||
setPermissionRequestHandler: vi.fn(),
|
||||
setPermissionCheckHandler: vi.fn(),
|
||||
setUserAgent: vi.fn(),
|
||||
};
|
||||
sessions.set(partition, browserSession);
|
||||
@@ -59,6 +63,113 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("scope-a");
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
|
||||
const browserSession = sessions.get(partition);
|
||||
assert.isDefined(browserSession);
|
||||
|
||||
const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
|
||||
const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
|
||||
assert.isFunction(requestHandler);
|
||||
assert.isFunction(checkHandler);
|
||||
|
||||
const requestAllows = (permission: string): boolean => {
|
||||
let granted: boolean | undefined;
|
||||
requestHandler(null, permission, (value: boolean) => {
|
||||
granted = value;
|
||||
});
|
||||
assert.isDefined(granted);
|
||||
return granted;
|
||||
};
|
||||
|
||||
for (const permission of [
|
||||
"clipboard-read",
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
]) {
|
||||
assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
|
||||
assert.isTrue(
|
||||
checkHandler(null, permission) as boolean,
|
||||
`check handler should allow ${permission}`,
|
||||
);
|
||||
}
|
||||
|
||||
// `clipboard-write` is not a real Electron permission — the async write API
|
||||
// uses `clipboard-sanitized-write` — so the stale name must not be granted,
|
||||
// and unrelated permissions stay denied.
|
||||
for (const permission of ["clipboard-write", "midi"]) {
|
||||
assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
|
||||
assert.isFalse(
|
||||
checkHandler(null, permission) as boolean,
|
||||
`check handler should deny ${permission}`,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "digest",
|
||||
cause: nativeCause,
|
||||
});
|
||||
const failingCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: () => Effect.fail(platformCause),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to derive a desktop preview browser partition for scope environment-a.",
|
||||
);
|
||||
assert.notInclude(error.message, nativeCause.message);
|
||||
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
|
||||
});
|
||||
|
||||
it.effect("preserves session scope, partition, and the Electron failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("Electron session failed");
|
||||
fromPartition.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("environment-b");
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -80,4 +191,52 @@ describe("BrowserSession", () => {
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
const firstPartition = yield* browserSessions.getPartition("scope-a");
|
||||
const secondPartition = yield* browserSessions.getPartition("scope-b");
|
||||
const firstSession = sessions.get(firstPartition);
|
||||
const secondSession = sessions.get(secondPartition);
|
||||
assert.isDefined(firstSession);
|
||||
assert.isDefined(secondSession);
|
||||
|
||||
const storageCause = new Error("storage clear failed");
|
||||
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
storageError.message,
|
||||
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
|
||||
);
|
||||
assert.notInclude(storageError.message, storageCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
}
|
||||
|
||||
const cacheCause = new Error("cache clear failed");
|
||||
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
cacheError.message,
|
||||
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
|
||||
);
|
||||
assert.notInclude(cacheError.message, cacheCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -5,31 +5,101 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
// Permissions granted to preview web content. `clipboard-sanitized-write` is the
|
||||
// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
|
||||
// `clipboard-write`, which is not a valid Electron permission name. Async
|
||||
// clipboard writes are gated by the permission *check* handler (not only the
|
||||
// request handler), so both handlers must allow it; otherwise built-in "Copy"
|
||||
// buttons — e.g. the Next.js / Vercel error overlay — fail with
|
||||
// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
|
||||
const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-read",
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
{
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
scope: Schema.String,
|
||||
cause: Schema.instanceOf(PlatformError.PlatformError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
|
||||
"BrowserSessionCreationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
|
||||
"BrowserSessionStorageClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
|
||||
"BrowserSessionCacheClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
BrowserSessionStorageClearError,
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
@@ -38,11 +108,15 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(scope))
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
|
||||
);
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
scope,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
@@ -60,14 +134,21 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
.replace(/\s*t3code\/[\d.]+/, "");
|
||||
browserSession.setUserAgent(userAgent);
|
||||
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
|
||||
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
|
||||
callback(allowed.includes(permission));
|
||||
callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
|
||||
});
|
||||
browserSession.setPermissionCheckHandler((_webContents, permission) =>
|
||||
ALLOWED_PREVIEW_PERMISSIONS.has(permission),
|
||||
);
|
||||
const next = new Map(sessions);
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCreationError({
|
||||
scope,
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -79,13 +160,17 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionStorageClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
@@ -94,10 +179,14 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCacheClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
|
||||
@@ -1,30 +1,43 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, vi } from "vite-plus/test";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -41,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -78,7 +92,9 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
const withManager = <A>(
|
||||
use: (
|
||||
@@ -93,6 +109,8 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -128,6 +146,72 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
for (const value of Array.isArray(message) ? message : [message]) {
|
||||
if (typeof value === "object" && value !== null && "cause" in value) {
|
||||
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
|
||||
}
|
||||
}
|
||||
});
|
||||
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform: "darwin",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
cause: new Error("renderer unavailable"),
|
||||
});
|
||||
const delivered = vi.fn();
|
||||
|
||||
return withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
delivered(tabId, state);
|
||||
}),
|
||||
);
|
||||
|
||||
const state = yield* manager.createTab("tab_listener_failure");
|
||||
|
||||
expect(delivered).toHaveBeenCalledOnce();
|
||||
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
|
||||
expect(loggedErrors).toHaveLength(1);
|
||||
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
|
||||
expect(loggedErrors[0]).toMatchObject({
|
||||
operation: "send-window-message",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Logger.layer([logger], {
|
||||
mergeWithExisting: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
effectIt.effect("does not swallow state listener interruption", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.interrupt);
|
||||
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -180,6 +264,197 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -237,6 +512,20 @@ describe("PreviewManager", () => {
|
||||
expect(artifact.path).toMatch(
|
||||
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
|
||||
);
|
||||
|
||||
const captureCause = new Error("capture failed");
|
||||
capturePage.mockRejectedValueOnce(captureCause);
|
||||
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewOperationError",
|
||||
operation: "captureScreenshot.capturePage",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause: captureCause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -302,9 +591,12 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -324,8 +616,20 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
message: "Preview artifact path is outside the configured artifact directory.",
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewArtifactPathOutsideDirectoryError",
|
||||
artifactPath: "/tmp/t3/dev/settings.json",
|
||||
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
|
||||
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
|
||||
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
|
||||
expect(Exit.isFailure(invalidImageExit)).toBe(true);
|
||||
if (Exit.isSuccess(invalidImageExit)) return;
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
|
||||
_tag: "PreviewArtifactImageLoadError",
|
||||
artifactPath,
|
||||
});
|
||||
}),
|
||||
),
|
||||
@@ -380,7 +684,11 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
Effect.sync(() => {
|
||||
activity.push(event.phase);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const click = yield* manager
|
||||
@@ -408,6 +716,178 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -466,10 +946,174 @@ describe("PreviewManager", () => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error.cause).toMatchObject({
|
||||
name: "PreviewAutomationControlInterruptedError",
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationControlInterruptedError",
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
});
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
if (error instanceof Error) {
|
||||
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
|
||||
}
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const text = "ReferenceError: fallbackDetail is not defined";
|
||||
const exceptionDetails = {
|
||||
text,
|
||||
exception: { description: "" },
|
||||
};
|
||||
const sendCommand = vi.fn(async (method: string) =>
|
||||
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
|
||||
);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const exit = yield* Effect.exit(
|
||||
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PreviewAutomationEvaluationError",
|
||||
detailKind: "exception-text",
|
||||
detailLength: text.length,
|
||||
cause: exceptionDetails,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("PreviewOperationError", () => {
|
||||
it("keeps timeline detail separate from its structured message", () => {
|
||||
const cause = new Error("CDP command failed with an invalid node id");
|
||||
const error = new PreviewManager.PreviewOperationError({
|
||||
operation: "click.DOM.resolveNode",
|
||||
tabId: "tab_1",
|
||||
webContentsId: 42,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Preview automation diagnostics", () => {
|
||||
it("keeps browser exception detail out of structural diagnostics", () => {
|
||||
const secret = "unrelated-browser-payload-secret";
|
||||
const detail = "ReferenceError: missingValue is not defined";
|
||||
const cause = {
|
||||
text: "Uncaught Error",
|
||||
exception: { description: detail },
|
||||
unsafePayload: secret,
|
||||
};
|
||||
const error = new PreviewManager.PreviewAutomationEvaluationError({
|
||||
tabId: "tab_1",
|
||||
detailKind: "exception-description",
|
||||
detailLength: detail.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
|
||||
expect("detail" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
|
||||
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
|
||||
secret,
|
||||
);
|
||||
});
|
||||
|
||||
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
|
||||
const selector = "role=button[name='selector-secret']";
|
||||
const reason = "Unexpected token near reason-secret";
|
||||
const cause = { invalidSelector: true as const, message: reason };
|
||||
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
|
||||
operation: "click",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
cause,
|
||||
});
|
||||
|
||||
const encoded = encodePreviewManagerError(error);
|
||||
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
|
||||
readonly cause?: unknown;
|
||||
};
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodedCause).toStrictEqual(cause);
|
||||
expect(error).toMatchObject({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
reasonLength: reason.length,
|
||||
});
|
||||
expect(error.detail).toEqual({
|
||||
selectorKind: "locator",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
|
||||
expect("selector" in error).toBe(false);
|
||||
expect("reason" in error).toBe(false);
|
||||
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
|
||||
reason,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not retain a missing target locator", () => {
|
||||
const selector = "[data-token='target-secret']";
|
||||
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
|
||||
operation: "scroll",
|
||||
tabId: "tab_1",
|
||||
selectorKind: "selector",
|
||||
selectorLength: selector.length,
|
||||
});
|
||||
|
||||
expect(error.message).not.toContain(selector);
|
||||
expect(JSON.stringify(error)).not.toContain(selector);
|
||||
expect("locator" in error).toBe(false);
|
||||
});
|
||||
});
|
||||
+1014
-429
File diff suppressed because it is too large.
Load diff
@@ -3,10 +3,14 @@ import * as Effect from "effect/Effect";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractPlaywrightInjectedRuntimeSource,
|
||||
playwrightInjectedRuntimeInstallExpression,
|
||||
playwrightInjectedRuntimeSource,
|
||||
} from "./PlaywrightInjectedRuntime.ts";
|
||||
|
||||
const bundleWithSourceLiteral = (literal: string): string =>
|
||||
`const source3 = ${literal};\n }\n});`;
|
||||
|
||||
describe("playwright injected runtime", () => {
|
||||
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -23,4 +27,54 @@ describe("playwright injected runtime", () => {
|
||||
expect(expression).toContain('testIdAttributeName":"data-testid');
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("reports a missing source marker without an artificial cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceMarkerNotFoundError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
marker: "source3 = ",
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps source validation metadata cause-free", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(
|
||||
bundleWithSourceLiteral('"short"'),
|
||||
"/tmp/coreBundle.js",
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceValidationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
actualType: "string",
|
||||
actualLength: 5,
|
||||
minimumLength: 100_000,
|
||||
});
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves the source evaluation cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlaywrightSourceEvaluationError",
|
||||
bundlePath: "/tmp/coreBundle.js",
|
||||
timeoutMs: 1_000,
|
||||
cause: expect.objectContaining({ name: "SyntaxError" }),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -4,69 +4,180 @@ import * as NodeModule from "node:module";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeVM from "node:vm";
|
||||
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
|
||||
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
|
||||
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
|
||||
const PLAYWRIGHT_BROWSER_NAME = "chromium";
|
||||
|
||||
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
|
||||
"PlaywrightInjectedRuntimeError",
|
||||
)<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Playwright injected runtime operation failed: ${this.operation}`;
|
||||
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
|
||||
"PlaywrightPackageResolveError",
|
||||
{
|
||||
specifier: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to resolve Playwright package: ${this.specifier}`;
|
||||
}
|
||||
}
|
||||
|
||||
const fail = (operation: string, cause: unknown) =>
|
||||
new PlaywrightInjectedRuntimeError({ operation, cause });
|
||||
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()(
|
||||
"PlaywrightCoreBundleReadError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
|
||||
"PlaywrightSourceMarkerNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
marker: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
|
||||
"PlaywrightSourceTerminatorNotFoundError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
terminator: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
|
||||
"PlaywrightSourceEvaluationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
|
||||
"PlaywrightSourceValidationError",
|
||||
{
|
||||
bundlePath: Schema.String,
|
||||
actualType: Schema.String,
|
||||
actualLength: Schema.NullOr(Schema.Number),
|
||||
minimumLength: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const actual =
|
||||
this.actualLength === null
|
||||
? this.actualType
|
||||
: `${this.actualType} with ${this.actualLength} characters`;
|
||||
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
|
||||
"PlaywrightOptionsEncodeError",
|
||||
{
|
||||
sdkLanguage: Schema.String,
|
||||
browserName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const PlaywrightInjectedRuntimeError = Schema.Union([
|
||||
PlaywrightPackageResolveError,
|
||||
PlaywrightCoreBundleReadError,
|
||||
PlaywrightSourceMarkerNotFoundError,
|
||||
PlaywrightSourceTerminatorNotFoundError,
|
||||
PlaywrightSourceEvaluationError,
|
||||
PlaywrightSourceValidationError,
|
||||
PlaywrightOptionsEncodeError,
|
||||
]);
|
||||
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
|
||||
|
||||
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
|
||||
"PlaywrightInjectedRuntime.extractSource",
|
||||
)(function* (coreBundle: string, bundlePath: string) {
|
||||
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
|
||||
if (start < 0) {
|
||||
return yield* new PlaywrightSourceMarkerNotFoundError({
|
||||
bundlePath,
|
||||
marker: PLAYWRIGHT_SOURCE_MARKER,
|
||||
});
|
||||
}
|
||||
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
|
||||
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* new PlaywrightSourceTerminatorNotFoundError({
|
||||
bundlePath,
|
||||
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
|
||||
});
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () =>
|
||||
NodeVM.runInNewContext(literal, Object.create(null), {
|
||||
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new PlaywrightSourceEvaluationError({
|
||||
bundlePath,
|
||||
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
|
||||
return yield* new PlaywrightSourceValidationError({
|
||||
bundlePath,
|
||||
actualType: typeof source,
|
||||
actualLength: typeof source === "string" ? source.length : null,
|
||||
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
|
||||
});
|
||||
}
|
||||
return source;
|
||||
});
|
||||
|
||||
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
|
||||
function* () {
|
||||
const packageJsonPath = yield* Effect.try({
|
||||
try: () => require.resolve("playwright-core/package.json"),
|
||||
catch: (cause) => fail("resolvePackage", cause),
|
||||
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
|
||||
catch: (cause) =>
|
||||
new PlaywrightPackageResolveError({
|
||||
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
|
||||
const coreBundle = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
NodeFSP.readFile(
|
||||
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
|
||||
"utf8",
|
||||
),
|
||||
catch: (cause) => fail("readCoreBundle", cause),
|
||||
try: () => NodeFSP.readFile(bundlePath, "utf8"),
|
||||
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
|
||||
});
|
||||
const marker = "source3 = ";
|
||||
const start = coreBundle.indexOf(marker);
|
||||
if (start < 0) {
|
||||
return yield* fail(
|
||||
"findSourceMarker",
|
||||
new Error("Playwright injected runtime marker was not found."),
|
||||
);
|
||||
}
|
||||
const literalStart = start + marker.length;
|
||||
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
|
||||
if (literalEnd < 0) {
|
||||
return yield* fail(
|
||||
"findSourceTerminator",
|
||||
new Error("Playwright injected runtime terminator was not found."),
|
||||
);
|
||||
}
|
||||
const literal = coreBundle.slice(literalStart, literalEnd);
|
||||
const source = yield* Effect.try({
|
||||
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
|
||||
catch: (cause) => fail("evaluateSourceLiteral", cause),
|
||||
});
|
||||
if (typeof source !== "string" || source.length < 100_000) {
|
||||
return yield* fail(
|
||||
"validateSource",
|
||||
new Error("Playwright injected runtime extraction returned invalid source."),
|
||||
);
|
||||
}
|
||||
return source;
|
||||
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -76,14 +187,23 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
|
||||
const source = yield* playwrightInjectedRuntimeSource();
|
||||
const options = yield* encodeUnknownJson({
|
||||
isUnderTest: false,
|
||||
sdkLanguage: "javascript",
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
testIdAttributeName: "data-testid",
|
||||
stableRafCount: 1,
|
||||
browserName: "chromium",
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
shouldPrependErrorPrefix: false,
|
||||
isUtilityWorld: false,
|
||||
customEngines: [],
|
||||
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PlaywrightOptionsEncodeError({
|
||||
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
|
||||
browserName: PLAYWRIGHT_BROWSER_NAME,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return `(() => {
|
||||
if (globalThis.__t3PlaywrightInjected) return true;
|
||||
const module = { exports: {} };
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -11,11 +11,26 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
}),
|
||||
),
|
||||
),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),
|
||||
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
|
||||
@@ -87,11 +102,16 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
});
|
||||
@@ -109,11 +129,16 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
@@ -205,20 +230,44 @@ describe("DesktopSettings", () => {
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"mainWindowBounds": { "x": 120, "y": 80, "width": 1280, "height": 900 },
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects window bounds that do not satisfy the domain schema", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
|
||||
mainWindowMaximized: true,
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
|
||||
const loaded = yield* settings.load;
|
||||
assert.isNull(loaded.mainWindowBounds);
|
||||
assert.isFalse(loaded.mainWindowMaximized);
|
||||
assert.equal(loaded.serverExposureMode, "network-accessible");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -226,12 +275,15 @@ describe("DesktopSettings", () => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
|
||||
yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
|
||||
yield* settings.setServerExposureMode("network-accessible");
|
||||
|
||||
const persisted = yield* decodeDesktopSettingsPatch(
|
||||
yield* fileSystem.readFileString(environment.desktopSettingsPath),
|
||||
);
|
||||
assert.deepEqual(persisted, {
|
||||
mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
|
||||
mainWindowMaximized: true,
|
||||
serverExposureMode: "network-accessible",
|
||||
} satisfies typeof DesktopSettingsPatch.Type);
|
||||
}),
|
||||
@@ -248,11 +300,16 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -270,11 +327,16 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -291,13 +353,108 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const enable = yield* settings.setWslBackendEnabled(true);
|
||||
assert.isTrue(enable.changed);
|
||||
assert.equal(enable.settings.wslBackendEnabled, true);
|
||||
|
||||
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
|
||||
assert.isTrue(distro.changed);
|
||||
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reloaded = yield* settings.load;
|
||||
assert.equal(reloaded.wslBackendEnabled, true);
|
||||
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reject = yield* settings.setWslDistro("bad name!");
|
||||
assert.equal(reject.settings.wslDistro, null);
|
||||
|
||||
const noop = yield* settings.setWslDistro(null);
|
||||
assert.isFalse(noop.changed);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const persistedFallback = yield* settings.applyWslWindowsFallback;
|
||||
assert.isTrue(persistedFallback.changed);
|
||||
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(persistedFallback.settings.wslOnly, false);
|
||||
|
||||
const persistedReload = yield* settings.load;
|
||||
assert.equal(persistedReload.wslBackendEnabled, false);
|
||||
assert.equal(persistedReload.wslOnly, false);
|
||||
|
||||
yield* settings.setWslBackendEnabled(true);
|
||||
yield* settings.setWslOnly(true);
|
||||
|
||||
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
|
||||
assert.isTrue(volatileFallback.changed);
|
||||
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
|
||||
assert.equal(volatileFallback.settings.wslOnly, false);
|
||||
|
||||
const current = yield* settings.get;
|
||||
assert.equal(current.wslBackendEnabled, false);
|
||||
assert.equal(current.wslOnly, false);
|
||||
|
||||
const diskReload = yield* settings.load;
|
||||
assert.equal(diskReload.wslBackendEnabled, true);
|
||||
assert.equal(diskReload.wslOnly, true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslMode: "wsl",
|
||||
wslDistro: "Ubuntu-22.04",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops invalid persisted wsl distro values on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslBackendEnabled: true,
|
||||
wslDistro: "bad/name",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslBackendEnabled, true);
|
||||
assert.equal(loaded.wslDistro, null);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -17,13 +17,31 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
// Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
|
||||
// integration. We now run Windows and WSL backends side by side, so the
|
||||
// setting is just whether the WSL backend should be running alongside the
|
||||
// primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
|
||||
// value are migrated to `wslBackendEnabled: true` on load.
|
||||
readonly wslBackendEnabled: boolean;
|
||||
readonly wslDistro: string | null;
|
||||
// When true (and wslBackendEnabled is also true) the desktop runs only
|
||||
// the WSL backend as the primary, and the Windows-side Node backend is
|
||||
// not started. Designed for users who develop entirely inside WSL and
|
||||
// don't want a second backend process running. Defaults to false so
|
||||
// existing setups stay on the parallel-backends behavior. Changing
|
||||
// this requires a desktop restart because the pool's primary spec is
|
||||
// chosen once at layer init.
|
||||
readonly wslOnly: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopSettingsChange {
|
||||
@@ -32,21 +50,57 @@ export interface DesktopSettingsChange {
|
||||
}
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
const MIN_MAIN_WINDOW_SIZE = {
|
||||
width: 840,
|
||||
height: 620,
|
||||
} as const;
|
||||
export const DesktopWindowBoundsSchema = Schema.Struct({
|
||||
x: Schema.Int,
|
||||
y: Schema.Int,
|
||||
width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.width)),
|
||||
height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.height)),
|
||||
});
|
||||
export type DesktopWindowBounds = typeof DesktopWindowBoundsSchema.Type;
|
||||
export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
width: 1100,
|
||||
height: 780,
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslBackendEnabled: false,
|
||||
wslDistro: null,
|
||||
wslOnly: false,
|
||||
};
|
||||
|
||||
const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
width: Schema.Number,
|
||||
height: Schema.Number,
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
// Newer form of the WSL toggle. `wslMode` is still accepted on load so
|
||||
// existing on-disk settings keep working; on the next persist we write the
|
||||
// new boolean and the legacy key drops out.
|
||||
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
wslOnly: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
|
||||
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
|
||||
@@ -55,6 +109,8 @@ type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
||||
const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
|
||||
const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
|
||||
const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
|
||||
const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema);
|
||||
const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema);
|
||||
|
||||
const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
|
||||
settings,
|
||||
@@ -83,17 +139,15 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
{
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setMainWindowBounds: (
|
||||
bounds: DesktopWindowBounds,
|
||||
isMaximized: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
@@ -104,6 +158,20 @@ export class DesktopAppSettings extends Context.Service<
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslBackendEnabled: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslDistro: (
|
||||
distro: string | null,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslOnly: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly applyWslWindowsFallback: Effect.Effect<
|
||||
DesktopSettingsChange,
|
||||
DesktopSettingsWriteError
|
||||
>;
|
||||
readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
@@ -120,18 +188,36 @@ function normalizeTailscaleServePort(value: unknown): number {
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
function normalizeWslDistro(value: unknown): string | null {
|
||||
return typeof value === "string" && isValidDistroName(value) ? value : null;
|
||||
}
|
||||
|
||||
export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | null {
|
||||
return Option.getOrNull(decodeDesktopWindowBounds(value));
|
||||
}
|
||||
|
||||
function normalizeDesktopSettingsDocument(
|
||||
parsed: DesktopSettingsDocument,
|
||||
appVersion: string,
|
||||
): DesktopSettings {
|
||||
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
|
||||
const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds);
|
||||
const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
|
||||
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
|
||||
const updateChannelConfiguredByUser =
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
|
||||
|
||||
// Newer form wins when both are present; otherwise fall back to the legacy
|
||||
// `wslMode === "wsl"` signal so users coming off the swap-mode build keep
|
||||
// their WSL backend enabled.
|
||||
const wslBackendEnabled =
|
||||
parsed.wslBackendEnabled === true ||
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
||||
@@ -140,6 +226,9 @@ function normalizeDesktopSettingsDocument(
|
||||
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
wslBackendEnabled,
|
||||
wslDistro: normalizeWslDistro(parsed.wslDistro),
|
||||
wslOnly: parsed.wslOnly === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,6 +238,12 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
if (settings.mainWindowMaximized) {
|
||||
document.mainWindowMaximized = true;
|
||||
}
|
||||
if (settings.serverExposureMode !== defaults.serverExposureMode) {
|
||||
document.serverExposureMode = settings.serverExposureMode;
|
||||
}
|
||||
@@ -164,6 +259,15 @@ function toDesktopSettingsDocument(
|
||||
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
|
||||
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
|
||||
}
|
||||
if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
|
||||
document.wslBackendEnabled = settings.wslBackendEnabled;
|
||||
}
|
||||
if (settings.wslDistro !== defaults.wslDistro) {
|
||||
document.wslDistro = settings.wslDistro;
|
||||
}
|
||||
if (settings.wslOnly !== defaults.wslOnly) {
|
||||
document.wslOnly = settings.wslOnly;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
@@ -180,6 +284,22 @@ function setServerExposureMode(
|
||||
};
|
||||
}
|
||||
|
||||
function setMainWindowBounds(
|
||||
settings: DesktopSettings,
|
||||
bounds: DesktopWindowBounds,
|
||||
isMaximized: boolean,
|
||||
): DesktopSettings {
|
||||
return settings.mainWindowBounds !== null &&
|
||||
desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) &&
|
||||
settings.mainWindowMaximized === isMaximized
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
mainWindowBounds: bounds,
|
||||
mainWindowMaximized: isMaximized,
|
||||
};
|
||||
}
|
||||
|
||||
function setTailscaleServe(
|
||||
settings: DesktopSettings,
|
||||
input: { readonly enabled: boolean; readonly port: Option.Option<number> },
|
||||
@@ -210,6 +330,38 @@ function setUpdateChannel(
|
||||
};
|
||||
}
|
||||
|
||||
function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslBackendEnabled === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslBackendEnabled: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
|
||||
const normalized = normalizeWslDistro(distro);
|
||||
return settings.wslDistro === normalized
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslDistro: normalized,
|
||||
};
|
||||
}
|
||||
|
||||
function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
|
||||
return settings.wslOnly === enabled
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslOnly: enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
|
||||
return setWslOnly(setWslBackendEnabled(settings, false), false);
|
||||
}
|
||||
|
||||
function readSettings(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
@@ -244,18 +396,46 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.settingsPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
|
||||
);
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -265,6 +445,12 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
|
||||
const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
|
||||
SynchronizedRef.modify(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
|
||||
});
|
||||
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
@@ -276,8 +462,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.desktopSettingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
@@ -303,6 +494,18 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setMainWindowBounds: (bounds, isMaximized) =>
|
||||
persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
|
||||
Effect.withSpan("desktop.settings.setMainWindowBounds", {
|
||||
attributes: {
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
isMaximized,
|
||||
},
|
||||
}),
|
||||
),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
@@ -315,6 +518,26 @@ export const make = Effect.gen(function* () {
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
|
||||
),
|
||||
setWslDistro: (distro) =>
|
||||
persist((settings) => setWslDistro(settings, distro)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslDistro", {
|
||||
attributes: { distro: distro ?? null },
|
||||
}),
|
||||
),
|
||||
setWslOnly: (enabled) =>
|
||||
persist((settings) => setWslOnly(settings, enabled)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
|
||||
),
|
||||
applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
|
||||
),
|
||||
applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
|
||||
Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -340,10 +563,18 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: SynchronizedRef.get(settingsRef),
|
||||
setMainWindowBounds: (bounds, isMaximized) =>
|
||||
update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
|
||||
setServerExposureMode: (mode) =>
|
||||
update((settings) => setServerExposureMode(settings, mode)),
|
||||
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
|
||||
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
|
||||
setWslBackendEnabled: (enabled) =>
|
||||
update((settings) => setWslBackendEnabled(settings, enabled)),
|
||||
setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
|
||||
setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
|
||||
applyWslWindowsFallback: update(applyWslWindowsFallback),
|
||||
applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,129 @@
|
||||
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 Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
interface LogRecord {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const baseDir = "/virtual-home";
|
||||
|
||||
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopClientSettings.layer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
|
||||
);
|
||||
}
|
||||
|
||||
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
|
||||
const records: Array<LogRecord> = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
records.push({
|
||||
message,
|
||||
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
|
||||
});
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
return {
|
||||
result: yield* settings.get,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
records,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeLayer(fileSystemLayer),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClientSettings diagnostics", () => {
|
||||
it.effect("treats a missing settings file as expected without warning", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(FileSystem.layerNoop({}));
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.deepEqual(result.records, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs non-missing filesystem failures with the settings path", () => {
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0]?.message, [
|
||||
"Could not read desktop client settings.",
|
||||
permissionError,
|
||||
]);
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("logs malformed settings documents with the settings path", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.succeed("{not-json"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
const message = result.records[0]?.message;
|
||||
if (!Array.isArray(message)) {
|
||||
return assert.fail("expected structured warning arguments");
|
||||
}
|
||||
assert.equal(message[0], "Could not decode desktop client settings.");
|
||||
const schemaError = message[1];
|
||||
if (schemaError === null || typeof schemaError !== "object") {
|
||||
return assert.fail("expected the schema error in the warning");
|
||||
}
|
||||
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -5,6 +5,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 * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -17,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -28,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
@@ -117,11 +118,13 @@ describe("DesktopClientSettings", () => {
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.exists(error.cause);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.isString(error.cause.stack);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, error.cause.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -25,7 +25,9 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
|
||||
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
|
||||
decodeLegacyClientSettingsDocumentJson(raw).pipe(
|
||||
Effect.map((document) => document.settings),
|
||||
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
|
||||
Effect.catchTags({
|
||||
SchemaError: () => decodeClientSettingsJsonValue(raw),
|
||||
}),
|
||||
);
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
@@ -36,7 +38,6 @@ const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
|
||||
"DesktopClientSettingsWriteError",
|
||||
@@ -51,13 +52,6 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopClientSettingsWriteError =>
|
||||
new DesktopClientSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
{
|
||||
@@ -73,14 +67,29 @@ const readClientSettings = (
|
||||
settingsPath: string,
|
||||
): Effect.Effect<Option.Option<ClientSettings>> =>
|
||||
fileSystem.readFileString(settingsPath).pipe(
|
||||
Effect.option,
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<string>()),
|
||||
),
|
||||
}),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
|
||||
onSome: (raw) =>
|
||||
decodeClientSettingsJson(raw).pipe(
|
||||
Effect.map((settings) => Option.some(settings)),
|
||||
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
@@ -96,19 +105,45 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.settingsPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -124,8 +159,13 @@ export const make = Effect.gen(function* () {
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopClientSettingsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.clientSettingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
|
||||
@@ -271,10 +271,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces typed safe storage availability failures", () => {
|
||||
it.effect("adds saved-environment context to safe storage availability failures", () => {
|
||||
const cause = new Error("safe storage unavailable");
|
||||
return withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
|
||||
@@ -285,8 +286,22 @@ describe("DesktopSavedEnvironments", () => {
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "check-encryption-availability");
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
const availabilityError =
|
||||
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
|
||||
assert.strictEqual(availabilityError.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notEqual(error.message, availabilityError.message);
|
||||
}),
|
||||
{ availabilityError: cause },
|
||||
);
|
||||
|
||||
@@ -77,7 +77,12 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-secret",
|
||||
"decrypt-secret",
|
||||
]);
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
@@ -92,17 +97,6 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
{
|
||||
@@ -141,6 +135,20 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
|
||||
"DesktopSavedEnvironmentSecretProtectionError",
|
||||
{
|
||||
operation: DesktopSavedEnvironmentSecretProtectionOperation,
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
@@ -152,11 +160,11 @@ export type DesktopSavedEnvironmentsMutationError =
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
@@ -276,19 +284,45 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "encode-registry",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "replace-registry-file",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.registryPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -341,8 +375,13 @@ export const make = Effect.gen(function* () {
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
@@ -396,7 +435,21 @@ export const make = Effect.gen(function* () {
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
if (Option.isNone(encoded)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
@@ -405,7 +458,19 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
return Option.some(
|
||||
yield* safeStorage.decryptString(secretBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "decrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
@@ -415,11 +480,34 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "encrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
const isDesktopShellEnvironmentCommandError = Schema.is(
|
||||
DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
|
||||
);
|
||||
|
||||
function envOutput(values: Readonly<Record<string, string>>): string {
|
||||
return Object.entries(values)
|
||||
.flatMap(([name, value]) => [
|
||||
@@ -59,6 +67,7 @@ function runShellEnvironment(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly handler: (command: ChildProcess.Command) => string;
|
||||
readonly failure?: PlatformError.PlatformError;
|
||||
}) {
|
||||
const environmentLayer = Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
@@ -68,7 +77,11 @@ function runShellEnvironment(input: {
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
|
||||
ChildProcessSpawner.make((command) =>
|
||||
input.failure === undefined
|
||||
? Effect.succeed(makeProcess(input.handler(command)))
|
||||
: Effect.fail(input.failure),
|
||||
),
|
||||
);
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
@@ -229,4 +242,44 @@ describe("DesktopShellEnvironment", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: "/bin/bash",
|
||||
});
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
|
||||
return runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () => "",
|
||||
failure: cause,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
const errors = messages
|
||||
.flatMap((message) => (Array.isArray(message) ? message : [message]))
|
||||
.filter(isDesktopShellEnvironmentCommandError);
|
||||
assert.lengthOf(errors, 1);
|
||||
assert.equal(errors[0]?.probe, "login-shell");
|
||||
assert.equal(errors[0]?.executable, "bash");
|
||||
assert.equal(errors[0]?.argumentCount, 2);
|
||||
assert.notProperty(errors[0] ?? {}, "args");
|
||||
assert.equal(errors[0]?.cause, cause);
|
||||
assert.notInclude(errors[0]?.message ?? "", cause.message);
|
||||
}),
|
||||
),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1356 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user