Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
929d35a1e8 | ||
|
|
32c6012dab | ||
|
|
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 | ||
|
|
9faf5533eb | ||
|
|
03a9e682f1 | ||
|
|
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 | ||
|
|
97e5cd3bf7 | ||
|
|
b19fc1b87b | ||
|
|
2fa37ec183 | ||
|
|
db27502aff | ||
|
|
6c5fb7930d | ||
|
|
30acfa9c51 | ||
|
|
f58b6da230 | ||
|
|
9a1c4875a3 | ||
|
|
7eda6ba5fc | ||
|
|
c00e721c04 | ||
|
|
b0a3a50448 | ||
|
|
79c57170c7 | ||
|
|
3900c45f25 | ||
|
|
8d61172f8b | ||
|
|
dc82f792c3 | ||
|
|
335e0b59ea | ||
|
|
2fbbe68c24 | ||
|
|
65385c0281 | ||
|
|
6d2dae0627 | ||
|
|
10a8d3fbd9 | ||
|
|
0ad1e9d9e4 | ||
|
|
2f8d3baa88 | ||
|
|
6b74476322 | ||
|
|
d9e9539862 | ||
|
|
7118e43d16 | ||
|
|
4e8ee13d8f | ||
|
|
b17b6d50c5 | ||
|
|
ccf8331600 | ||
|
|
ffae12f329 | ||
|
|
01cd564557 | ||
|
|
4ee719a094 | ||
|
|
01492ebd3b | ||
|
|
93fd972108 | ||
|
|
df1540f3ac | ||
|
|
d5a72d5be1 | ||
|
|
742dd7af0d | ||
|
|
5c1ac92257 | ||
|
|
8bfdacf206 | ||
|
|
b6302784f8 | ||
|
|
9544e72d08 | ||
|
|
938b19a6bb | ||
|
|
3b56dc17a5 | ||
|
|
d2c0a6a48f | ||
|
|
1cf3647da6 | ||
|
|
53d0107759 | ||
|
|
60b16d1f28 | ||
|
|
ab0baaa886 | ||
|
|
753bc4672d | ||
|
|
e29ad7604b | ||
|
|
cdaba7fa8b | ||
|
|
fbf6263876 | ||
|
|
c08b968f4e | ||
|
|
d9f59be704 | ||
|
|
a4446e263d | ||
|
|
494350cc0b | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 | ||
|
|
3bdaa6e100 | ||
|
|
b7b00bfb9d | ||
|
|
ae2b523503 | ||
|
|
75b3b3c48a | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 | ||
|
|
3a0623f1cd | ||
|
|
cd91ec75f3 | ||
|
|
d4ba9e9618 | ||
|
|
c1792bc9a6 | ||
|
|
1b4317ec35 | ||
|
|
f452d63fef | ||
|
|
18a49abcec | ||
|
|
85d5df6256 | ||
|
|
b5b769dddf | ||
|
|
3c7862edd7 | ||
|
|
d8fe3d72c8 | ||
|
|
70ec39ae80 | ||
|
|
3d9e8dea7d | ||
|
|
f7c422d581 | ||
|
|
dd739c880d | ||
|
|
6c6740e381 | ||
|
|
29150b5736 | ||
|
|
07c6d70b91 | ||
|
|
50bc18b208 | ||
|
|
63d42a5e58 | ||
|
|
9b43123ba2 | ||
|
|
17fb0e4a9a | ||
|
|
43e8bbd7ae | ||
|
|
52c77c1ec4 | ||
|
|
d6eb386e3d | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e | ||
|
|
0e4a43519f | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 | ||
|
|
b76f161d55 | ||
|
|
75257d64e9 | ||
|
|
e1ce9f8500 | ||
|
|
602148f8fe |
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,71 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
|
||||
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
|
||||
|
||||
## Start an isolated web environment
|
||||
|
||||
1. Run commands from the repository root.
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
2. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
|
||||
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
```
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
|
||||
|
||||
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
|
||||
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
|
||||
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
|
||||
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Finish the test
|
||||
|
||||
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
|
||||
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
|
||||
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
|
||||
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
|
||||
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and seed isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
|
||||
@@ -0,0 +1,58 @@
|
||||
# SQLite fixtures
|
||||
|
||||
Load this reference only when inspecting or seeding local T3 state directly.
|
||||
|
||||
## Select the correct database
|
||||
|
||||
When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
|
||||
|
||||
Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
|
||||
|
||||
## Use the helper
|
||||
|
||||
List tables:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
|
||||
```
|
||||
|
||||
Inspect current columns before writing a fixture:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "PRAGMA table_info(projection_threads)"
|
||||
```
|
||||
|
||||
Apply a SQL fixture from a file:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts exec \
|
||||
--base-dir <base-dir> \
|
||||
--file /tmp/t3-seed.sql
|
||||
```
|
||||
|
||||
Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
|
||||
|
||||
## Seed projection data carefully
|
||||
|
||||
The web UI primarily reads these projection tables:
|
||||
|
||||
- `projection_projects`
|
||||
- `projection_threads`
|
||||
- `projection_thread_messages`
|
||||
- `projection_thread_activities`
|
||||
- `projection_thread_sessions`
|
||||
- `projection_turns`
|
||||
- `projection_pending_approvals`
|
||||
- `projection_thread_proposed_plans`
|
||||
|
||||
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
|
||||
|
||||
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
|
||||
|
||||
Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
|
||||
|
||||
Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
|
||||
@@ -0,0 +1,188 @@
|
||||
---
|
||||
name: test-t3-mobile
|
||||
description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
|
||||
---
|
||||
|
||||
# Test T3 Mobile
|
||||
|
||||
Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
|
||||
|
||||
Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
|
||||
|
||||
## Select a viable platform
|
||||
|
||||
Inspect the host and the affected code before launching processes:
|
||||
|
||||
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
|
||||
- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
|
||||
- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
|
||||
|
||||
Do not treat unavailable iOS tooling as a blocker when Android is a valid representative target.
|
||||
|
||||
## Choose the lightest valid launch path
|
||||
|
||||
- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
|
||||
- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
|
||||
- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
|
||||
- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
|
||||
|
||||
The development identity on both platforms is:
|
||||
|
||||
- App: `T3 Code Dev`
|
||||
- Bundle/package identifier: `com.t3tools.t3code.dev`
|
||||
- URL scheme: `t3code-dev`
|
||||
|
||||
Bundle or package presence proves the correct variant, not native compatibility. Reuse it only when the current changes did not alter its Expo SDK, native dependencies, config plugins, entitlements, generated project, or native source.
|
||||
|
||||
## Start one disposable T3 environment
|
||||
|
||||
Run backend commands from the repository root. Use the ignored, worktree-local `.t3` directory or create a fresh directory with the host OS's temporary-directory mechanism. An explicit base directory stores state in `<base-dir>/userdata`; never point testing at shared `~/.t3` state.
|
||||
|
||||
Seed a small number of meaningful Git projects before starting the backend:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts project add <git-workspace> \
|
||||
--base-dir <base-dir> \
|
||||
--title <project-title>
|
||||
```
|
||||
|
||||
Running `project add` before the backend starts gives it exclusive offline database access. If a backend is already running, wait until it is ready so the CLI dispatches through the live server; never run offline mutations concurrently with the server.
|
||||
|
||||
Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
|
||||
|
||||
Start a headless backend after seeding:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts serve \
|
||||
--host 127.0.0.1 \
|
||||
--port <server-port> \
|
||||
--base-dir <base-dir> \
|
||||
--no-browser
|
||||
```
|
||||
|
||||
Use these client origins:
|
||||
|
||||
- iOS Simulator: `http://127.0.0.1:<server-port>`
|
||||
- Android Emulator: `http://10.0.2.2:<server-port>`
|
||||
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
|
||||
|
||||
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
Run Metro from `apps/mobile`.
|
||||
|
||||
1. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
|
||||
2. Never kill another worktree's Metro. Use a free explicit port when necessary.
|
||||
3. Run `vp run dev:client` on the standard port. For another port, retain the complete development identity:
|
||||
|
||||
```bash
|
||||
APP_VARIANT=development vp exec expo start \
|
||||
--dev-client \
|
||||
--scheme t3code-dev \
|
||||
--clear \
|
||||
--lan \
|
||||
--port <metro-port>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:APP_VARIANT = "development"` first and then run the `vp exec expo start ...` command without the leading assignment.
|
||||
|
||||
4. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
|
||||
|
||||
### iOS launch
|
||||
|
||||
Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
|
||||
|
||||
- Workspace: `<repo>/apps/mobile/ios/T3CodeDev.xcworkspace`
|
||||
- Scheme: `T3CodeDev`
|
||||
- Configuration: `Debug`
|
||||
- Simulator ID: the selected UDID
|
||||
- Bundle ID: `com.t3tools.t3code.dev`
|
||||
|
||||
Check the installed client with:
|
||||
|
||||
```bash
|
||||
xcrun simctl get_app_container <simulator-udid> com.t3tools.t3code.dev app
|
||||
xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
|
||||
```
|
||||
|
||||
Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
|
||||
|
||||
### Android launch
|
||||
|
||||
Select one running emulator serial from `adb devices` and check the installed client:
|
||||
|
||||
```bash
|
||||
adb -s <emulator-serial> shell pm path com.t3tools.t3code.dev
|
||||
adb -s <emulator-serial> reverse tcp:<metro-port> tcp:<metro-port>
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d '<printed-dev-client-url>' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--base-url <mobile-origin> \
|
||||
--ttl 15m \
|
||||
--label agent-mobile-<short-device-id>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
## Drive and observe the affected flow
|
||||
|
||||
### iOS
|
||||
|
||||
Use `snapshot_ui` and current element references from XcodeBuildMCP for taps and typing. Stream the same UDID through `ios-simulator-browser` so the user can watch in T3 Code when the host supports it. Use the stream as a visual feed rather than a reason to switch to fragile browser coordinates.
|
||||
|
||||
### Android
|
||||
|
||||
Prefer semantic Android automation exposed by the current agent host. Otherwise inspect the current hierarchy with `adb shell uiautomator dump`, target stable resource IDs, content descriptions, text, or bounds, and use scoped `adb shell input` actions. Refresh the hierarchy after navigation. Capture the final state with `adb exec-out screencap -p`.
|
||||
|
||||
Android does not use serve-sim. Use a browser-compatible Android mirror when the host already provides one; otherwise return focused emulator screenshots as evidence rather than installing unrelated streaming infrastructure during verification.
|
||||
|
||||
## Verify and clean up
|
||||
|
||||
Exercise only the affected flow on one representative device unless the change specifically concerns platform, OS version, or screen size. Before finishing:
|
||||
|
||||
1. Confirm the app connected to the intended disposable environment instead of merely rendering an empty disconnected state.
|
||||
2. Capture the relevant final state.
|
||||
3. Remove the disposable environment from T3 Code Dev.
|
||||
4. Remove any `adb reverse` rule created for this test with `adb -s <emulator-serial> reverse --remove tcp:<metro-port>`.
|
||||
5. Stop only the serve-sim, Metro, backend, emulator, and log processes started by this test.
|
||||
6. Remove only base directories and temporary Git repositories deliberately created for this test. Preserve them when they contain useful reproduction evidence.
|
||||
|
||||
Keep local verification focused. Do not turn this workflow into a full repository test run.
|
||||
|
||||
## Troubleshoot predictable failures
|
||||
|
||||
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
|
||||
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
|
||||
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
|
||||
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
|
||||
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
|
||||
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Test T3 Mobile"
|
||||
short_description: "Test T3 Code on iOS or Android"
|
||||
default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
|
||||
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
-2
@@ -1,5 +1,5 @@
|
||||
# Optional: T3 Cloud source builds
|
||||
# Leave these unset to disable optional T3 Cloud features in local source builds.
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
@@ -8,5 +8,21 @@
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
# returns a different RP ID or when multiple domains must be entitled.
|
||||
# T3CODE_APPLE_TEAM_ID=ABC1234567
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
test:
|
||||
name: Test
|
||||
@@ -60,52 +61,6 @@ jobs:
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
test_browser:
|
||||
name: Test Browser
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: vp run --filter @t3tools/web test:browser:install
|
||||
|
||||
- name: Browser test / Chat view
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
|
||||
|
||||
- name: Browser test / Chat markdown
|
||||
working-directory: apps/web
|
||||
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
|
||||
|
||||
- name: Browser test / Components
|
||||
working-directory: apps/web
|
||||
run: |
|
||||
vp test run --mode browser --browser=chromium \
|
||||
src/components/GitActionsControl.browser.tsx \
|
||||
src/components/KeybindingsToast.browser.tsx \
|
||||
src/components/ThreadTerminalDrawer.browser.tsx \
|
||||
src/components/chat/MessagesTimeline.browser.tsx \
|
||||
src/components/chat/ProviderModelPicker.browser.tsx \
|
||||
src/components/chat/CompactComposerControlsMenu.browser.tsx \
|
||||
src/components/settings/SettingsPanels.browser.tsx
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Deploy T3 Cloud relay
|
||||
name: Deploy T3 Connect relay
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -2,10 +2,12 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -55,7 +57,10 @@ jobs:
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
packager: pnpm
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -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
|
||||
@@ -167,7 +167,7 @@ jobs:
|
||||
--github-output
|
||||
|
||||
relay_public_config:
|
||||
name: Resolve T3 Cloud public config
|
||||
name: Resolve T3 Connect public config
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
@@ -180,12 +180,46 @@ jobs:
|
||||
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
relay_url: ${{ steps.public_config.outputs.relay_url }}
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- id: relay_state
|
||||
name: Read production relay tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
vp run --filter t3code-relay deploy \
|
||||
--stage prod \
|
||||
--read-state \
|
||||
--github-output \
|
||||
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
|
||||
|
||||
- name: Upload relay client tracing config
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing.env
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- id: public_config
|
||||
name: Resolve production relay public config
|
||||
shell: bash
|
||||
@@ -218,10 +252,64 @@ jobs:
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
|
||||
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
|
||||
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
|
||||
# job — the Windows artifact then ships a ready WSL backend binary with no
|
||||
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
needs: [preflight]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Resolve node-pty from apps/server (where it's a dependency) and build
|
||||
# its native binary from source for Linux. node-addon-api resolves from
|
||||
# node-pty's own dependency tree, so node-gyp has everything it needs.
|
||||
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
|
||||
pty_dir="$(dirname "$pty_pkg")"
|
||||
( cd "$pty_dir" && npx --yes node-gyp rebuild )
|
||||
mkdir -p wsl-prebuild
|
||||
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
|
||||
file wsl-prebuild/pty.node
|
||||
|
||||
- name: Upload node-pty linux-x64 prebuild
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild/pty.node
|
||||
if-no-files-found: error
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: [preflight, relay_public_config]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
|
||||
# available to download, but only the Windows matrix entry consumes it. We
|
||||
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
|
||||
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
|
||||
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
|
||||
# build_wsl_node_pty failed; the Windows-only download step below then fails
|
||||
# that single platform if the prebuild is missing.
|
||||
needs: [preflight, relay_public_config, build_wsl_node_pty]
|
||||
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -272,9 +360,30 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Download WSL node-pty prebuild
|
||||
if: matrix.platform == 'win'
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
@@ -377,6 +486,9 @@ jobs:
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
|
||||
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
|
||||
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
@@ -404,15 +516,31 @@ jobs:
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
|
||||
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
|
||||
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
|
||||
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
|
||||
security cms -D -i "$profile_path" >/dev/null
|
||||
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
|
||||
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
|
||||
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
|
||||
# so the packaged WSL backend ships a ready binary (no first-launch
|
||||
# compile). Required for a working WSL backend on Windows.
|
||||
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
@@ -508,6 +636,20 @@ jobs:
|
||||
- --filter=@t3tools/web...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -646,6 +788,7 @@ jobs:
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
@@ -670,6 +813,20 @@ jobs:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
@@ -715,7 +872,11 @@ jobs:
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=${T3CODE_CLERK_CLI_OAUTH_CLIENT_ID:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
|
||||
@@ -27,6 +27,9 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Dependency acquisition and runtime boundaries
|
||||
|
||||
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
|
||||
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
|
||||
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -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,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,33 @@
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
|
||||
- If changing native mobile code, `vp run lint:mobile` must also pass.
|
||||
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
|
||||
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
|
||||
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
|
||||
- Backend changes must include and run focused tests for the changed behavior.
|
||||
- Run targeted formatting, lint, and type checks for the affected scope when available.
|
||||
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
|
||||
- After frontend feature development or any user-visible frontend behavior change, the primary agent must run one integrated verification pass for each affected client surface after integrating the work:
|
||||
- Web: use the `test-t3-app` skill. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
|
||||
- Mobile: use the `test-t3-mobile` skill. Connect one representative iOS Simulator or Android Emulator available on the host to one isolated environment and verify the affected flow. On compatible macOS hosts, prefer iOS for cross-platform changes and stream it through serve-sim in the T3 Code in-app browser or another available agent browser; use Android when it is the affected or viable platform.
|
||||
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
|
||||
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
|
||||
|
||||
## Project Snapshot
|
||||
## Verifying Changes in the Browser
|
||||
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
Starting a dev server to verify changes is expected and allowed:
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
- `T3CODE_DEV_INSTANCE=<worktree-name> bun run dev` runs an isolated instance
|
||||
with deterministic port offsets (server base `13773`, web base `5733`; the
|
||||
runner probes for free ports and prints the chosen pair).
|
||||
- On localhost dev servers the web UI authenticates automatically — no pairing
|
||||
code needed. Just load the printed web port (e.g. `http://localhost:5733`).
|
||||
This applies to fresh/headless browser profiles too.
|
||||
- Dev instances sharing the default `T3CODE_HOME` (`~/.t3`) share state under
|
||||
`~/.t3/dev`; a browser session carries across instances on the same hostname.
|
||||
Use `localhost` consistently — it does not share cookies with `127.0.0.1`.
|
||||
|
||||
## Core Priorities
|
||||
|
||||
1. Performance first.
|
||||
2. Reliability first.
|
||||
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
See `docs/reference/scripts.md` for parallel-instance details and
|
||||
`docs/cloud/environment-auth.md` for how dev auto-auth is secured.
|
||||
|
||||
## Package Roles
|
||||
|
||||
@@ -35,7 +41,6 @@ Long term maintainability is a core priority. If you add new functionality, firs
|
||||
## Reference Repos
|
||||
|
||||
- Open-source Codex repo: https://github.com/openai/codex
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
@@ -47,8 +52,7 @@ agents.
|
||||
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
|
||||
- Do not edit files under `.repos/` unless explicitly asked.
|
||||
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
|
||||
- Manage vendored subtrees with `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one
|
||||
configured repository.
|
||||
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
|
||||
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
|
||||
`.repos/` matches the installed dependency version.
|
||||
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.24",
|
||||
"version": "0.0.28",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -12,6 +12,8 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/electron": "catalog:",
|
||||
"@clerk/electron-passkeys": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
@@ -20,13 +22,17 @@
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"electron": "41.5.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"electron-builder": "26.15.6",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import { compile } from "tailwindcss";
|
||||
|
||||
const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const appRoot = NodePath.join(directory, "..");
|
||||
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
|
||||
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
|
||||
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));
|
||||
|
||||
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
|
||||
NodeFSP.readFile(sourcePath, "utf8"),
|
||||
NodeFSP.readFile(preloadPath, "utf8"),
|
||||
NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
|
||||
NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
|
||||
]);
|
||||
|
||||
const candidates = new Set(
|
||||
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
|
||||
);
|
||||
const compilerInput = [
|
||||
themeSource,
|
||||
preflightSource,
|
||||
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
|
||||
].join("\n");
|
||||
const compiler = await compile(compilerInput, { base: appRoot });
|
||||
const css = compiler.build([...candidates]);
|
||||
const encodedCss = `'${css
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("'", "\\'")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\n", "\\n")}'`;
|
||||
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
|
||||
|
||||
await NodeFSP.writeFile(outputPath, moduleSource);
|
||||
@@ -1,8 +1,13 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import {
|
||||
desktopDir,
|
||||
resolveDevProtocolClient,
|
||||
resolveElectronLaunchCommand,
|
||||
} from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
@@ -29,6 +34,8 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
@@ -53,19 +60,21 @@ const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
if (hostPlatform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
@@ -79,7 +88,8 @@ function startApp() {
|
||||
const launchArgs = devProtocolClient
|
||||
? electronArgs
|
||||
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
|
||||
const app = spawn(resolveElectronPath(), launchArgs, {
|
||||
const electronCommand = resolveElectronLaunchCommand(launchArgs);
|
||||
const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
@@ -172,8 +182,8 @@ function scheduleRestart() {
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(
|
||||
join(desktopDir, directory),
|
||||
const watcher = NodeFS.watch(
|
||||
NodePath.join(desktopDir, directory),
|
||||
{ persistent: true },
|
||||
(_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
@@ -189,12 +199,14 @@ function startWatchers() {
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
if (hostPlatform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
chmodSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
const repoRoot = resolve(desktopDir, "..", "..");
|
||||
const devBundleIdSuffix = basename(repoRoot)
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
export const desktopDir = NodePath.resolve(__dirname, "..");
|
||||
const repoRoot = NodePath.resolve(desktopDir, "..", "..");
|
||||
const devBundleIdSuffix = NodePath.basename(repoRoot)
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9]+/g, "");
|
||||
export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
@@ -30,29 +20,36 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 10;
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
|
||||
function resolveDevelopmentProtocolCallbackPort() {
|
||||
const configuredPort = Number.parseInt(process.env.T3CODE_PORT ?? "", 10);
|
||||
if (Number.isInteger(configuredPort) && configuredPort > 0 && configuredPort < 65535) {
|
||||
return configuredPort + 1;
|
||||
}
|
||||
return 13774;
|
||||
}
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
"assets",
|
||||
"dev",
|
||||
"blueprint-macos-1024.png",
|
||||
);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const replaceResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const insertResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-string", value, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -63,16 +60,24 @@ function setPlistString(plistPath, key, value) {
|
||||
|
||||
function setPlistJson(plistPath, key, value) {
|
||||
const serialized = JSON.stringify(value);
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-json", serialized, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const replaceResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-replace", key, "-json", serialized, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-json", serialized, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const insertResult = NodeChildProcess.spawnSync(
|
||||
"plutil",
|
||||
["-insert", key, "-json", serialized, plistPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -82,7 +87,7 @@ function setPlistJson(plistPath, key, value) {
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -95,39 +100,43 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = join(desktopDir, "dist-electron", "main.cjs");
|
||||
const protocolCallbackUrl = `http://127.0.0.1:${resolveDevelopmentProtocolCallbackPort()}/auth/callback`;
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
["T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED", "1"],
|
||||
["T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL", protocolCallbackUrl],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
writeFileSync(
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
'for arg in "$@"; do',
|
||||
' case "$arg" in',
|
||||
" t3code-dev://auth/callback*)",
|
||||
' if [ -n "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" ]; then',
|
||||
' /usr/bin/curl -fsS --max-time 2 -X POST --data-binary "$arg" "$T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL" >/dev/null 2>&1 && exit 0',
|
||||
" fi",
|
||||
" ;;",
|
||||
" esac",
|
||||
"done",
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
chmodSync(targetBinaryPath, 0o755);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
|
||||
function registerMacLauncherBundle(appBundlePath) {
|
||||
@@ -157,21 +166,24 @@ function registerMacLauncherBundle(appBundlePath) {
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (
|
||||
NodeFS.existsSync(generatedIconPath) &&
|
||||
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
|
||||
) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
|
||||
NodeFS.mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
@@ -181,7 +193,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
@@ -191,7 +203,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -204,15 +216,16 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
@@ -221,9 +234,9 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
},
|
||||
]);
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
|
||||
NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
@@ -235,7 +248,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
];
|
||||
|
||||
for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
|
||||
const infoPlistPath = join(
|
||||
const infoPlistPath = NodePath.join(
|
||||
appBundlePath,
|
||||
"Contents",
|
||||
"Frameworks",
|
||||
@@ -243,7 +256,7 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!existsSync(infoPlistPath)) {
|
||||
if (!NodeFS.existsSync(infoPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -259,77 +272,154 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
return JSON.parse(NodeFS.readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
|
||||
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
appProtocolSchemes: APP_PROTOCOL_SCHEMES,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
NodeFS.existsSync(launcherBinaryPath) &&
|
||||
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
// verbatimSymlinks keeps the framework's relative symlinks intact
|
||||
// (e.g. Resources -> Versions/Current/Resources). Without it cpSync
|
||||
// rewrites them to absolute paths into node_modules, which escape the
|
||||
// bundle and crash sandboxed helper processes (icudtl.dat not found).
|
||||
NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
patchMainBundleInfoPlist(
|
||||
targetAppBundlePath,
|
||||
iconPath,
|
||||
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
|
||||
);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
// Keep Electron's native executable inside the branded bundle. Launching the
|
||||
// node_modules copy makes macOS associate the process (and Dock label) with
|
||||
// Electron.app even though this bundle's Info.plist has the T3 Code name.
|
||||
// Its conventional executable name also keeps Electron's default-app runtime
|
||||
// in development mode instead of making app.isPackaged report true.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
}
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return targetBinaryPath;
|
||||
return launcherBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
if (hostPlatform !== "linux") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
|
||||
try {
|
||||
const sandboxStat = NodeFS.statSync(sandboxPath);
|
||||
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
|
||||
);
|
||||
return ["--no-sandbox"];
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
|
||||
export function resolveElectronLaunchCommand(args = []) {
|
||||
const electronPath = resolveElectronPath();
|
||||
return {
|
||||
electronPath,
|
||||
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveElectronBinaryPath({
|
||||
ensureRuntime = ensureElectronRuntime,
|
||||
createRequire = NodeModule.createRequire,
|
||||
moduleUrl = import.meta.url,
|
||||
} = {}) {
|
||||
ensureRuntime();
|
||||
|
||||
const require = createRequire(moduleUrl);
|
||||
return require("electron");
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (process.platform !== "darwin" || !isDevelopment) {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
appBundleId: APP_BUNDLE_ID,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
|
||||
it("repairs Electron before loading the package entrypoint", () => {
|
||||
const calls = [];
|
||||
const electronPath = resolveElectronBinaryPath({
|
||||
ensureRuntime: () => {
|
||||
calls.push("ensure");
|
||||
},
|
||||
createRequire: () => (specifier) => {
|
||||
calls.push(`require:${specifier}`);
|
||||
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
|
||||
},
|
||||
moduleUrl: import.meta.url,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
electronPath,
|
||||
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
|
||||
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
|
||||
const paths = resolveMacLauncherPaths(
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
|
||||
"T3 Code (Dev)",
|
||||
);
|
||||
|
||||
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
|
||||
assert.equal(
|
||||
paths.launcherBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
|
||||
);
|
||||
assert.equal(
|
||||
paths.runtimeElectronBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
|
||||
);
|
||||
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: paths.runtimeElectronBinaryPath,
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {},
|
||||
});
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,17 @@
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeModule from "node:module";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone repair script has no Effect runtime.
|
||||
const hostArch = NodeOS.arch();
|
||||
|
||||
function getPlatformPath() {
|
||||
switch (process.platform) {
|
||||
switch (hostPlatform) {
|
||||
case "darwin":
|
||||
return "Electron.app/Contents/MacOS/Electron";
|
||||
case "freebsd":
|
||||
@@ -17,32 +21,34 @@ function getPlatformPath() {
|
||||
case "win32":
|
||||
return "electron.exe";
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
|
||||
throw new Error(`Electron builds are not available on platform: ${hostPlatform}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExecutable(filePath) {
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(filePath, 0o755);
|
||||
if (hostPlatform !== "win32") {
|
||||
NodeFS.chmodSync(filePath, 0o755);
|
||||
}
|
||||
}
|
||||
|
||||
function repairPathFile(electronDir, platformPath) {
|
||||
const pathFile = join(electronDir, "path.txt");
|
||||
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
|
||||
const pathFile = NodePath.join(electronDir, "path.txt");
|
||||
const currentPath = NodeFS.existsSync(pathFile)
|
||||
? NodeFS.readFileSync(pathFile, "utf8")
|
||||
: undefined;
|
||||
|
||||
if (currentPath !== platformPath) {
|
||||
writeFileSync(pathFile, platformPath);
|
||||
NodeFS.writeFileSync(pathFile, platformPath);
|
||||
}
|
||||
}
|
||||
|
||||
function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
const paths = [join(electronDir, "dist", platformPath)];
|
||||
const paths = [NodePath.join(electronDir, "dist", platformPath)];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
if (hostPlatform === "darwin") {
|
||||
paths.push(
|
||||
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
join(
|
||||
NodePath.join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
|
||||
NodePath.join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -58,11 +64,11 @@ function getRequiredRuntimePaths(electronDir, platformPath) {
|
||||
}
|
||||
|
||||
function isMachO(filePath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const result = spawnSync("file", ["-b", filePath], {
|
||||
const result = NodeChildProcess.spawnSync("file", ["-b", filePath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
@@ -71,18 +77,18 @@ function isMachO(filePath) {
|
||||
|
||||
function missingRuntimePaths(electronDir, platformPath) {
|
||||
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
|
||||
return !existsSync(runtimePath);
|
||||
return !NodeFS.existsSync(runtimePath);
|
||||
});
|
||||
}
|
||||
|
||||
function invalidRuntimePaths(electronDir, platformPath) {
|
||||
if (process.platform !== "darwin") {
|
||||
if (hostPlatform !== "darwin") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
join(electronDir, "dist", platformPath),
|
||||
join(
|
||||
NodePath.join(electronDir, "dist", platformPath),
|
||||
NodePath.join(
|
||||
electronDir,
|
||||
"dist",
|
||||
"Electron.app",
|
||||
@@ -91,11 +97,11 @@ function invalidRuntimePaths(electronDir, platformPath) {
|
||||
"Electron Framework.framework",
|
||||
"Electron Framework",
|
||||
),
|
||||
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
].filter((runtimePath) => NodeFS.existsSync(runtimePath) && !isMachO(runtimePath));
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
const result = NodeChildProcess.spawnSync(command, args, {
|
||||
encoding: "utf8",
|
||||
stdio: "inherit",
|
||||
});
|
||||
@@ -110,45 +116,45 @@ function runChecked(command, args) {
|
||||
}
|
||||
|
||||
function installElectronRuntime(electronDir, version) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
|
||||
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-"));
|
||||
const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`);
|
||||
|
||||
try {
|
||||
runChecked("curl", [
|
||||
"-fsSL",
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
|
||||
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`,
|
||||
"-o",
|
||||
zipPath,
|
||||
]);
|
||||
if (process.platform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
|
||||
if (hostPlatform === "darwin") {
|
||||
runChecked("ditto", ["-x", "-k", zipPath, NodePath.join(electronDir, "dist")]);
|
||||
} else {
|
||||
runChecked("python3", [
|
||||
"-c",
|
||||
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
|
||||
zipPath,
|
||||
join(electronDir, "dist"),
|
||||
NodePath.join(electronDir, "dist"),
|
||||
]);
|
||||
}
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureElectronRuntime() {
|
||||
const electronPackageJsonPath = require.resolve("electron/package.json");
|
||||
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = dirname(electronPackageJsonPath);
|
||||
const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8"));
|
||||
const electronDir = NodePath.dirname(electronPackageJsonPath);
|
||||
const platformPath = getPlatformPath();
|
||||
const electronPath = join(electronDir, "dist", platformPath);
|
||||
const electronPath = NodePath.join(electronDir, "dist", platformPath);
|
||||
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
|
||||
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
|
||||
|
||||
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
|
||||
if (existsSync(join(electronDir, "dist"))) {
|
||||
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
|
||||
if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) {
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true });
|
||||
}
|
||||
rmSync(join(electronDir, "path.txt"), { force: true });
|
||||
NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true });
|
||||
installElectronRuntime(electronDir, electronPackageJson.version);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const desktopDir = NodePath.resolve(__dirname, "..");
|
||||
const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
const child = spawn(electronBin, [mainJs], {
|
||||
const electronCommand = resolveElectronLaunchCommand([mainJs]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
|
||||
const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeNet from "node:net";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
await NodeFSP.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -16,7 +16,7 @@ async function fileExists(filePath) {
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
const socket = NodeNet.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
@@ -47,7 +47,7 @@ async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, conn
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
const ready = await fileExists(NodePath.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
@@ -114,6 +114,6 @@ export async function waitForResources({
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
await NodeTimersPromises.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -11,17 +11,20 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
@@ -32,22 +35,24 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
class DesktopBackendPortUnavailableError extends Data.TaggedError(
|
||||
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
|
||||
"DesktopBackendPortUnavailableError",
|
||||
)<{
|
||||
readonly startPort: number;
|
||||
readonly maxPort: number;
|
||||
readonly hosts: readonly string[];
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
startPort: Schema.Int,
|
||||
maxPort: Schema.Int,
|
||||
hosts: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
|
||||
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
|
||||
"DesktopDevelopmentBackendPortRequiredError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "T3CODE_PORT is required in desktop development.";
|
||||
}
|
||||
}
|
||||
@@ -100,12 +105,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
| DesktopLifecycle.DesktopShutdown
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronDialog.ElectronDialog
|
||||
> {
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -132,11 +137,14 @@ const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
|
||||
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
|
||||
|
||||
const bootstrap = Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const primaryBackend = yield* pool.primary;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* logBootstrapInfo("bootstrap start");
|
||||
|
||||
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
|
||||
@@ -163,6 +171,16 @@ const bootstrap = Effect.gen(function* () {
|
||||
}
|
||||
const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
|
||||
const backendConfig = yield* serverExposure.backendConfig;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const rendererTarget = environment.isDevelopment
|
||||
? Option.getOrThrow(environment.devServerUrl)
|
||||
: backendConfig.httpBaseUrl;
|
||||
yield* electronProtocol.registerDesktopProtocol({
|
||||
scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
|
||||
targetOrigin: rendererTarget,
|
||||
backendOrigin: backendConfig.httpBaseUrl,
|
||||
clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
|
||||
});
|
||||
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
|
||||
baseUrl: backendConfig.httpBaseUrl.href,
|
||||
});
|
||||
@@ -176,12 +194,24 @@ const bootstrap = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
yield* installDesktopIpcHandlers;
|
||||
yield* installDesktopIpcHandlers();
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
|
||||
if (!(yield* Ref.get(state.quitting))) {
|
||||
yield* backendManager.start;
|
||||
// In wsl-only mode the renderer is served by the WSL backend, which can be
|
||||
// slow to cold-boot — show a "Connecting to WSL" splash immediately so the
|
||||
// app feels responsive instead of presenting no window until WSL is ready.
|
||||
// (Dual mode opens fast off the Windows primary, so no splash there.)
|
||||
if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
|
||||
yield* desktopWindow.showConnectingSplash;
|
||||
}
|
||||
yield* primaryBackend.start;
|
||||
yield* logBootstrapInfo("bootstrap backend start requested");
|
||||
// Bring up the WSL backend if the user previously enabled it. The
|
||||
// primary is already starting; reconcile fires off the WSL register
|
||||
// in parallel rather than blocking primary readiness on a possibly
|
||||
// slow first wsl.exe spawn.
|
||||
yield* Effect.forkScoped(wslBackend.reconcile);
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.bootstrap"));
|
||||
|
||||
@@ -189,9 +219,8 @@ const startup = Effect.gen(function* () {
|
||||
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
@@ -209,7 +238,7 @@ const startup = Effect.gen(function* () {
|
||||
|
||||
yield* appIdentity.configure;
|
||||
yield* lifecycle.register;
|
||||
yield* cloudAuth.configure;
|
||||
yield* clerk.configure;
|
||||
|
||||
yield* electronApp.whenReady.pipe(
|
||||
Effect.withSpan("desktop.electron.whenReady"),
|
||||
@@ -218,7 +247,6 @@ const startup = Effect.gen(function* () {
|
||||
yield* logStartupInfo("app ready");
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* electronProtocol.registerDesktopFileProtocol;
|
||||
yield* updates.configure;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
@@ -229,11 +257,21 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
// Stop every backend in the pool, not just the primary. The
|
||||
// electronApp.quit() path can race ahead of the layer-scope
|
||||
// cascade, so leaving the WSL instance for its parent scope
|
||||
// finalizer means it gets hard-killed by the OS instead of
|
||||
// receiving SIGTERM + grace. Stops run concurrently.
|
||||
const instances = yield* pool.list;
|
||||
yield* Effect.forEach(instances, (instance) => instance.stop(), {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
}).pipe(Effect.ensuring(shutdown.markComplete)),
|
||||
);
|
||||
|
||||
yield* startup;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
DesktopBackendPortUnavailableError,
|
||||
DesktopDevelopmentBackendPortRequiredError,
|
||||
} from "./DesktopApp.ts";
|
||||
|
||||
describe("DesktopApp errors", () => {
|
||||
it("preserves unavailable backend port context", () => {
|
||||
const error = new DesktopBackendPortUnavailableError({
|
||||
startPort: 3_773,
|
||||
maxPort: 65_535,
|
||||
hosts: ["127.0.0.1", "0.0.0.0", "::"],
|
||||
});
|
||||
|
||||
assert.equal(error.startPort, 3_773);
|
||||
assert.equal(error.maxPort, 65_535);
|
||||
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the required development port", () => {
|
||||
const error = new DesktopDevelopmentBackendPortRequiredError();
|
||||
|
||||
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
@@ -63,7 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronAppShape);
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
@@ -73,7 +74,7 @@ const makeAssetsLayer = (png: Option.Option<string>) =>
|
||||
png,
|
||||
}),
|
||||
resolveResourcePath: () => Effect.succeed(Option.none()),
|
||||
} satisfies DesktopAssets.DesktopAssetsShape);
|
||||
} satisfies DesktopAssets.DesktopAssets["Service"]);
|
||||
|
||||
const makeEnvironmentLayer = (overrides: TestEnvironmentInput = {}) => {
|
||||
const { env, ...environmentOverrides } = overrides;
|
||||
@@ -105,6 +106,7 @@ const withIdentity = <A, E, R>(
|
||||
readonly calls?: ElectronAppCalls;
|
||||
readonly environment?: TestEnvironmentInput;
|
||||
readonly legacyPathExists?: boolean;
|
||||
readonly legacyPathProbeError?: PlatformError.PlatformError;
|
||||
readonly packageJson?: string;
|
||||
readonly pngIconPath?: Option.Option<string>;
|
||||
} = {},
|
||||
@@ -121,7 +123,11 @@ const withIdentity = <A, E, R>(
|
||||
Layer.provideMerge(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) =>
|
||||
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
}),
|
||||
@@ -147,6 +153,33 @@ describe("DesktopAppIdentity", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: legacyPath,
|
||||
});
|
||||
|
||||
return withIdentity(
|
||||
Effect.gen(function* () {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
|
||||
assert.equal(error.legacyPath, legacyPath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
|
||||
);
|
||||
}),
|
||||
{ legacyPathProbeError: cause },
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("configures app identity from the environment commit override", () => {
|
||||
const calls: ElectronAppCalls = {
|
||||
setAboutPanelOptions: [],
|
||||
|
||||
@@ -18,14 +18,24 @@ const AppPackageMetadata = Schema.Struct({
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
export interface DesktopAppIdentityShape {
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
|
||||
"DesktopUserDataPathResolutionError",
|
||||
{
|
||||
legacyPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
DesktopAppIdentityShape
|
||||
{
|
||||
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
@@ -35,7 +45,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -85,9 +95,15 @@ const make = Effect.gen(function* () {
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem
|
||||
.exists(legacyPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopAssets from "./DesktopAssets.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
describe("DesktopAssets", () => {
|
||||
it.effect("preserves the failed asset candidate and filesystem cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileName = "custom.bin";
|
||||
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "exists",
|
||||
pathOrDescriptor: candidatePath,
|
||||
description: "private filesystem diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
|
||||
});
|
||||
const assetsLayer = DesktopAssets.layer.pipe(
|
||||
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
|
||||
);
|
||||
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
|
||||
|
||||
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
|
||||
assert.equal(error.fileName, fileName);
|
||||
assert.equal(error.candidatePath, candidatePath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private filesystem diagnostic");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
@@ -12,27 +13,47 @@ export interface DesktopIconPaths {
|
||||
readonly png: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface DesktopAssetsShape {
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
|
||||
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
|
||||
"DesktopAssetProbeError",
|
||||
{
|
||||
fileName: Schema.String,
|
||||
candidatePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
) {}
|
||||
export class DesktopAssets extends Context.Service<
|
||||
DesktopAssets,
|
||||
{
|
||||
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
|
||||
readonly resolveResourcePath: (
|
||||
fileName: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopAssets") {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
fileName: string,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
DesktopAssetProbeError,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const candidates = environment.resolveResourcePathCandidates(fileName);
|
||||
for (const candidate of candidates) {
|
||||
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
|
||||
const exists = yield* fileSystem
|
||||
.exists(candidate)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
|
||||
),
|
||||
);
|
||||
if (exists) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
@@ -44,16 +65,23 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
ext: keyof DesktopIconPaths,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
DesktopAssetProbeError,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
if (environment.isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem
|
||||
.exists(developmentDockIconPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopAssetProbeError({
|
||||
fileName: "icon.png",
|
||||
candidatePath: developmentDockIconPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (developmentDockIconExists) {
|
||||
return Option.some(developmentDockIconPath);
|
||||
}
|
||||
@@ -62,7 +90,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
return yield* resolveResourcePath(`icon.${ext}`);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
>();
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
|
||||
createClerkBridgeMock: vi.fn(),
|
||||
storageAdapter: {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
storageMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron", () => ({
|
||||
createClerkBridge: createClerkBridgeMock,
|
||||
}));
|
||||
|
||||
vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClerk", () => {
|
||||
beforeEach(() => {
|
||||
createClerkBridgeMock.mockReset();
|
||||
storageMock.mockReset();
|
||||
});
|
||||
|
||||
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
|
||||
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
|
||||
|
||||
assert.equal(
|
||||
DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),
|
||||
"clerk.t3.codes",
|
||||
);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);
|
||||
assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);
|
||||
});
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme: "t3code-dev", host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge initialization failures", () => {
|
||||
const cause = new Error("bridge initialization failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves bridge cleanup failures", () => {
|
||||
const cause = new Error("bridge cleanup failed");
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({
|
||||
cleanup: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
|
||||
assert.equal(error.stateDir, "/tmp/t3-state");
|
||||
assert.equal(error.isDevelopment, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isDevelopment: true, scheme: "t3code-dev" },
|
||||
{ isDevelopment: false, scheme: "t3code" },
|
||||
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
|
||||
const bridge = { cleanup: vi.fn() };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);
|
||||
assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
{
|
||||
storage: storageAdapter,
|
||||
passkeys: true,
|
||||
renderer: { scheme, host: "app" },
|
||||
},
|
||||
],
|
||||
]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { createClerkBridge } from "@clerk/electron";
|
||||
import { storage } from "@clerk/electron/storage";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
|
||||
"DesktopClerkBridgeInitializationError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
|
||||
"DesktopClerkBridgeCleanupError",
|
||||
{
|
||||
stateDir: Schema.String,
|
||||
isDevelopment: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopClerk extends Context.Service<
|
||||
DesktopClerk,
|
||||
{
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopClerk") {}
|
||||
|
||||
export function resolveDesktopClerkFrontendApiHostname(
|
||||
publishableKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalizedKey = publishableKey?.trim();
|
||||
if (!normalizedKey) return undefined;
|
||||
|
||||
try {
|
||||
return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
|
||||
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? undefined
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
|
||||
);
|
||||
|
||||
export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
|
||||
return createClerkBridge({
|
||||
storage: storage({ path: stateDir }),
|
||||
passkeys: true,
|
||||
renderer: {
|
||||
scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
|
||||
host: ElectronProtocol.DESKTOP_HOST,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeInitializationError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(bridge) =>
|
||||
Effect.try({
|
||||
try: () => bridge.cleanup(),
|
||||
catch: (cause) =>
|
||||
new DesktopClerkBridgeCleanupError({
|
||||
stateDir: environment.stateDir,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
return DesktopClerk.of({
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
yield* electronApp.on("second-instance", () => {
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.clerk.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClerk, make);
|
||||
@@ -1,302 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopCloudAuth from "./DesktopCloudAuth.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthHarness {
|
||||
readonly app: ElectronApp.ElectronAppShape;
|
||||
readonly window: ElectronWindow.ElectronWindowShape;
|
||||
readonly listeners: Map<string, readonly ((...args: readonly unknown[]) => void)[]>;
|
||||
readonly protocolRegistrations: {
|
||||
readonly protocol: string;
|
||||
readonly path?: string;
|
||||
readonly args?: readonly string[];
|
||||
}[];
|
||||
readonly sends: { readonly channel: string; readonly args: readonly unknown[] }[];
|
||||
readonly reveals: unknown[];
|
||||
readonly layer: Layer.Layer<
|
||||
| DesktopCloudAuth.DesktopCloudAuth
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronWindow.ElectronWindow
|
||||
>;
|
||||
}
|
||||
|
||||
function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarness {
|
||||
const listeners = new Map<string, ((...args: readonly unknown[]) => void)[]>();
|
||||
const protocolRegistrations: CloudAuthHarness["protocolRegistrations"] = [];
|
||||
const sends: CloudAuthHarness["sends"] = [];
|
||||
const reveals: unknown[] = [];
|
||||
const mainWindow = { id: "main-window" };
|
||||
|
||||
const app = ElectronApp.ElectronApp.of({
|
||||
metadata: Effect.succeed({
|
||||
appVersion: "0.0.0-test",
|
||||
appPath: "/tmp/t3-code-test",
|
||||
isPackaged: !input.isDevelopment,
|
||||
resourcesPath: "/tmp/t3-code-test/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
Effect.sync(() => {
|
||||
protocolRegistrations.push({
|
||||
protocol,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(args === undefined ? {} : { args }),
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
const erasedListener = listener as (...args: readonly unknown[]) => void;
|
||||
listeners.set(eventName, [...(listeners.get(eventName) ?? []), erasedListener]);
|
||||
}),
|
||||
});
|
||||
|
||||
const window = ElectronWindow.ElectronWindow.of({
|
||||
create: () => Effect.die("not used"),
|
||||
main: Effect.succeed(Option.some(mainWindow as never)),
|
||||
currentMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
focusedMainOrFirst: Effect.succeed(Option.some(mainWindow as never)),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: (target) =>
|
||||
Effect.sync(() => {
|
||||
reveals.push(target);
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
sends.push({ channel, args });
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
});
|
||||
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
isDevelopment: input.isDevelopment,
|
||||
} as DesktopEnvironment.DesktopEnvironmentShape);
|
||||
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment);
|
||||
|
||||
return {
|
||||
app,
|
||||
window,
|
||||
listeners,
|
||||
protocolRegistrations,
|
||||
sends,
|
||||
reveals,
|
||||
layer: Layer.mergeAll(
|
||||
DesktopCloudAuth.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
Layer.succeed(ElectronApp.ElectronApp, app),
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, window),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function emitAppEvent(
|
||||
harness: CloudAuthHarness,
|
||||
eventName: string,
|
||||
...args: readonly unknown[]
|
||||
): void {
|
||||
for (const listener of harness.listeners.get(eventName) ?? []) {
|
||||
listener(...args);
|
||||
}
|
||||
}
|
||||
|
||||
const flushCloudAuthDispatch = Effect.promise(() => Promise.resolve());
|
||||
|
||||
describe("DesktopCloudAuth", () => {
|
||||
it("uses separate callback schemes for packaged and development builds", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: false }),
|
||||
"t3code",
|
||||
);
|
||||
assert.equal(
|
||||
DesktopCloudAuth.resolveCloudAuthCallbackScheme({ isDevelopment: true }),
|
||||
"t3code-dev",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only the expected scheme, host, path, and state", () => {
|
||||
assert.isNotNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "t3code://auth/callback?rotating_token_nonce=nonce&t3_state=wrong",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
assert.isNull(
|
||||
DesktopCloudAuth.parseCloudAuthCallbackUrl({
|
||||
rawUrl: "https://example.com/callback?rotating_token_nonce=nonce&t3_state=state-1",
|
||||
scheme: "t3code",
|
||||
state: "state-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a native development callback URL with request state", () => {
|
||||
assert.equal(
|
||||
DesktopCloudAuth.buildCloudAuthCallbackUrl({
|
||||
scheme: "t3code-dev",
|
||||
state: "state-1",
|
||||
}),
|
||||
"t3code-dev://auth/callback?t3_state=state-1",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("registers the development protocol client and dispatches matching callbacks", () => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
let prevented = false;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => (prevented = true) },
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.isTrue(prevented);
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.isString(harness.protocolRegistrations[0]?.path);
|
||||
assert.isArray(harness.protocolRegistrations[0]?.args);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.lengthOf(harness.reveals, 1);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("rejects mismatched callback state and only consumes the pending request once", () => {
|
||||
const harness = makeHarness({ isDevelopment: false });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const validCallback = new URL(redirectUrl);
|
||||
validCallback.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
const invalidCallback = new URL(validCallback);
|
||||
invalidCallback.searchParams.set(DesktopCloudAuth.CLOUD_AUTH_CALLBACK_STATE_PARAM, "wrong");
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
invalidCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
assert.deepEqual(harness.sends, []);
|
||||
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
emitAppEvent(
|
||||
harness,
|
||||
"open-url",
|
||||
{ preventDefault: () => undefined },
|
||||
validCallback.toString(),
|
||||
);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(
|
||||
harness.protocolRegistrations.map((registration) => registration.protocol),
|
||||
["t3code"],
|
||||
);
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [validCallback.toString()],
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"routes second-instance callbacks and reveals the window for non-callback launches",
|
||||
() => {
|
||||
const harness = makeHarness({ isDevelopment: true });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
yield* cloudAuth.configure;
|
||||
const redirectUrl = yield* cloudAuth.createRequest;
|
||||
const callbackUrl = new URL(redirectUrl);
|
||||
callbackUrl.searchParams.set("rotating_token_nonce", "nonce-1");
|
||||
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", callbackUrl.toString()]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
const revealCountAfterCallback = harness.reveals.length;
|
||||
emitAppEvent(harness, "second-instance", {}, ["electron", "--opened-from-dock"]);
|
||||
yield* flushCloudAuthDispatch;
|
||||
|
||||
assert.deepEqual(harness.sends, [
|
||||
{
|
||||
channel: IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
args: [callbackUrl.toString()],
|
||||
},
|
||||
]);
|
||||
assert.equal(revealCountAfterCallback, 1);
|
||||
assert.equal(harness.reveals.length, 2);
|
||||
}).pipe(Effect.provide(harness.layer), Effect.scoped);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,330 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import type * as Electron from "electron";
|
||||
|
||||
export const CLOUD_AUTH_CALLBACK_HOST = "auth";
|
||||
export const CLOUD_AUTH_CALLBACK_PATHNAME = "/callback";
|
||||
export const CLOUD_AUTH_CALLBACK_STATE_PARAM = "t3_state";
|
||||
export const CLOUD_AUTH_CALLBACK_SCHEME = "t3code";
|
||||
export const DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME = "t3code-dev";
|
||||
|
||||
const CLOUD_AUTH_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export class DesktopCloudAuthCallbackServerError extends Data.TaggedError(
|
||||
"DesktopCloudAuthCallbackServerError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to start the desktop cloud auth callback server.";
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingCloudAuthRequest {
|
||||
readonly state: string;
|
||||
readonly redirectUrl: string;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthShape {
|
||||
readonly createRequest: Effect.Effect<string, DesktopCloudAuthCallbackServerError>;
|
||||
readonly configure: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuth extends Context.Service<DesktopCloudAuth, DesktopCloudAuthShape>()(
|
||||
"@t3tools/desktop/app/DesktopCloudAuth",
|
||||
) {}
|
||||
|
||||
export function resolveCloudAuthCallbackScheme(input: { readonly isDevelopment: boolean }): string {
|
||||
return input.isDevelopment ? DEVELOPMENT_CLOUD_AUTH_CALLBACK_SCHEME : CLOUD_AUTH_CALLBACK_SCHEME;
|
||||
}
|
||||
|
||||
export function buildCloudAuthCallbackUrl(input: {
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): string {
|
||||
const url = new URL(
|
||||
`${input.scheme}://${CLOUD_AUTH_CALLBACK_HOST}${CLOUD_AUTH_CALLBACK_PATHNAME}`,
|
||||
);
|
||||
url.searchParams.set(CLOUD_AUTH_CALLBACK_STATE_PARAM, input.state);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function parseCloudAuthCallbackUrl(input: {
|
||||
readonly rawUrl: unknown;
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
if (typeof input.rawUrl !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(input.rawUrl);
|
||||
if (url.protocol !== `${input.scheme}:`) return null;
|
||||
if (url.hostname !== CLOUD_AUTH_CALLBACK_HOST) return null;
|
||||
if (url.pathname !== CLOUD_AUTH_CALLBACK_PATHNAME) return null;
|
||||
if (url.searchParams.get(CLOUD_AUTH_CALLBACK_STATE_PARAM) !== input.state) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function findCloudAuthCallbackUrl(input: {
|
||||
readonly values: readonly unknown[];
|
||||
readonly scheme: string;
|
||||
readonly state: string;
|
||||
}): URL | null {
|
||||
for (const value of input.values) {
|
||||
const url = parseCloudAuthCallbackUrl({
|
||||
rawUrl: value,
|
||||
scheme: input.scheme,
|
||||
state: input.state,
|
||||
});
|
||||
if (url) return url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveProtocolClientLaunchArgs(input: {
|
||||
readonly argv: readonly string[];
|
||||
}): readonly string[] {
|
||||
return input.argv.slice(1);
|
||||
}
|
||||
|
||||
function resolveConfiguredProtocolClient(): {
|
||||
readonly path: string;
|
||||
readonly args: readonly string[];
|
||||
} | null {
|
||||
const path = process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_PATH?.trim();
|
||||
if (!path) return null;
|
||||
|
||||
return {
|
||||
path,
|
||||
args: (process.env.T3CODE_DESKTOP_PROTOCOL_CLIENT_ARGS ?? "")
|
||||
.split("\n")
|
||||
.map((arg) => arg.trim())
|
||||
.filter((arg) => arg.length > 0),
|
||||
};
|
||||
}
|
||||
|
||||
function isProtocolRegistrationManagedExternally(): boolean {
|
||||
return process.env.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED?.trim() === "1";
|
||||
}
|
||||
|
||||
function resolveProtocolCallbackForwardUrl(): URL | null {
|
||||
const rawUrl = process.env.T3CODE_DESKTOP_PROTOCOL_CALLBACK_URL?.trim();
|
||||
if (!rawUrl) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "http:") return null;
|
||||
if (url.hostname !== "127.0.0.1") return null;
|
||||
if (url.pathname !== "/auth/callback") return null;
|
||||
if (!url.port) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const closeCloudAuthRequest = (request: PendingCloudAuthRequest | null): null => {
|
||||
request?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
function createCloudAuthRequestTimeout(onExpire: () => void): ReturnType<typeof setTimeout> {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Auth request expiry is tied to an Electron callback server, not fiber scheduling.
|
||||
return setTimeout(onExpire, CLOUD_AUTH_REQUEST_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function ignoreCloudAuthCallback(_rawUrl: string) {}
|
||||
|
||||
function startProtocolCallbackForwardServer(
|
||||
callbackUrl: URL,
|
||||
dispatch: (rawUrl: string) => void,
|
||||
): Effect.Effect<void, never, Scope.Scope> {
|
||||
const port = Number.parseInt(callbackUrl.port, 10);
|
||||
const routesLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/auth/callback",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const rawUrl = yield* request.text;
|
||||
yield* Effect.sync(() => {
|
||||
dispatch(rawUrl);
|
||||
});
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const NodeHttp = yield* Effect.promise(() => import("node:http"));
|
||||
const serverLayer = NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: callbackUrl.hostname,
|
||||
port,
|
||||
});
|
||||
yield* Layer.launch(HttpRouter.serve(routesLayer).pipe(Layer.provideMerge(serverLayer))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
let pendingAuthRequest: PendingCloudAuthRequest | null = null;
|
||||
let dispatchCloudAuthCallback: (rawUrl: string) => void = ignoreCloudAuthCallback;
|
||||
const makeCloudAuthRequestState = Effect.gen(function* () {
|
||||
const [left, right] = yield* Effect.all([crypto.randomUUIDv4, crypto.randomUUIDv4]);
|
||||
return `${left}${right}`.replaceAll("-", "");
|
||||
});
|
||||
|
||||
return DesktopCloudAuth.of({
|
||||
createRequest: Effect.gen(function* () {
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
const state = yield* makeCloudAuthRequestState.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthCallbackServerError({ cause })),
|
||||
);
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
|
||||
const redirectUrl = buildCloudAuthCallbackUrl({ scheme, state });
|
||||
const timeout = createCloudAuthRequestTimeout(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
});
|
||||
pendingAuthRequest = {
|
||||
state,
|
||||
redirectUrl,
|
||||
close: () => clearTimeout(timeout),
|
||||
};
|
||||
return redirectUrl;
|
||||
}),
|
||||
configure: Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const scope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const scheme = resolveCloudAuthCallbackScheme({
|
||||
isDevelopment: environment.isDevelopment,
|
||||
});
|
||||
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => {
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
}),
|
||||
);
|
||||
|
||||
if (isProtocolRegistrationManagedExternally()) {
|
||||
// Development macOS launchers set the default URL handler before the stock Electron
|
||||
// process starts so LaunchServices binds the scheme to the worktree-specific app bundle.
|
||||
} else if (environment.isDevelopment) {
|
||||
const configuredClient = resolveConfiguredProtocolClient();
|
||||
if (configuredClient) {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
configuredClient.path,
|
||||
configuredClient.args,
|
||||
);
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(
|
||||
scheme,
|
||||
process.execPath,
|
||||
resolveProtocolClientLaunchArgs({ argv: process.argv }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* electronApp.setAsDefaultProtocolClient(scheme);
|
||||
}
|
||||
|
||||
dispatchCloudAuthCallback = (rawUrl: string) => {
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? parseCloudAuthCallbackUrl({ rawUrl, scheme, state: pending.state })
|
||||
: null;
|
||||
if (!callbackUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
pendingAuthRequest = closeCloudAuthRequest(pendingAuthRequest);
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* electronWindow.sendAll(
|
||||
IpcChannels.CLOUD_AUTH_CALLBACK_CHANNEL,
|
||||
callbackUrl.toString(),
|
||||
);
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const protocolCallbackForwardUrl = resolveProtocolCallbackForwardUrl();
|
||||
if (environment.isDevelopment && protocolCallbackForwardUrl) {
|
||||
yield* startProtocolCallbackForwardServer(
|
||||
protocolCallbackForwardUrl,
|
||||
dispatchCloudAuthCallback,
|
||||
);
|
||||
}
|
||||
|
||||
const hasInstanceLock = yield* electronApp.requestSingleInstanceLock;
|
||||
if (!hasInstanceLock) {
|
||||
return yield* electronApp.quit;
|
||||
}
|
||||
|
||||
yield* electronApp.on<[Electron.Event, string]>("open-url", (event, rawUrl) => {
|
||||
event.preventDefault?.();
|
||||
dispatchCloudAuthCallback(rawUrl);
|
||||
});
|
||||
|
||||
yield* electronApp.on<[Electron.Event, readonly string[]]>(
|
||||
"second-instance",
|
||||
(_event, argv) => {
|
||||
const values = resolveProtocolClientLaunchArgs({ argv });
|
||||
const pending = pendingAuthRequest;
|
||||
const callbackUrl = pending
|
||||
? findCloudAuthCallbackUrl({ values, scheme, state: pending.state })
|
||||
: null;
|
||||
if (callbackUrl) {
|
||||
dispatchCloudAuthCallback(callbackUrl.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const mainWindow = yield* electronWindow.currentMainOrFirst;
|
||||
if (Option.isSome(mainWindow)) {
|
||||
yield* electronWindow.reveal(mainWindow.value);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuth.configure")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopCloudAuth, make);
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "./DesktopCloudAuthTokenStore.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
function makeSafeStorageLayer(input: { readonly available: boolean }) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(input.available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`enc:${value}`)),
|
||||
decryptString: (value) => {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
return Effect.fail(
|
||||
new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted token"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
}
|
||||
|
||||
function makeLayer(baseDir: string, input?: { readonly encryptionAvailable?: boolean }) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopCloudAuthTokenStore.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(makeSafeStorageLayer({ available: input?.encryptionAvailable ?? true })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
const withTokenStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore>,
|
||||
input?: { readonly encryptionAvailable?: boolean },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-cloud-auth-token-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, input)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopCloudAuthTokenStore", () => {
|
||||
it.effect("persists, reads, and clears the encrypted Clerk client JWT", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isTrue(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.some("__client=test.jwt"));
|
||||
|
||||
yield* tokenStore.clear;
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist a token when Electron safe storage is unavailable", () =>
|
||||
withTokenStore(
|
||||
Effect.gen(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
|
||||
assert.isFalse(yield* tokenStore.set("__client=test.jwt"));
|
||||
assert.deepStrictEqual(yield* tokenStore.get, Option.none());
|
||||
}),
|
||||
{ encryptionAvailable: false },
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
interface CloudAuthTokenDocument {
|
||||
readonly version: number;
|
||||
readonly encryptedClientJwt: string;
|
||||
}
|
||||
|
||||
const CloudAuthTokenDocumentSchema = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
encryptedClientJwt: Schema.String,
|
||||
});
|
||||
|
||||
const CloudAuthTokenDocumentJson = fromLenientJson(CloudAuthTokenDocumentSchema);
|
||||
const decodeCloudAuthTokenDocumentJson = Schema.decodeEffect(CloudAuthTokenDocumentJson);
|
||||
const encodeCloudAuthTokenDocumentJson = Schema.encodeEffect(CloudAuthTokenDocumentJson);
|
||||
|
||||
export class DesktopCloudAuthTokenStoreWriteError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop cloud auth token: ${this.cause.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStoreDecodeError extends Data.TaggedError(
|
||||
"DesktopCloudAuthTokenStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop cloud auth token.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopCloudAuthTokenStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopCloudAuthTokenStoreDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
token: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopCloudAuthTokenStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopCloudAuthTokenStore extends Context.Service<
|
||||
DesktopCloudAuthTokenStore,
|
||||
DesktopCloudAuthTokenStoreShape
|
||||
>()("@t3tools/desktop/app/DesktopCloudAuthTokenStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopCloudAuthTokenStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreDecodeError({ cause })),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
tokenPath: string,
|
||||
): Effect.Effect<Option.Option<CloudAuthTokenDocument>> =>
|
||||
fileSystem.readFileString(tokenPath).pipe(
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<CloudAuthTokenDocument>()),
|
||||
onSome: (raw) => decodeCloudAuthTokenDocumentJson(raw).pipe(Effect.option),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.cloudAuthTokenStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly tokenPath: string;
|
||||
readonly document: CloudAuthTokenDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
const directory = input.path.dirname(input.tokenPath);
|
||||
const tempPath = `${input.tokenPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeCloudAuthTokenDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.tokenPath);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopCloudAuthTokenStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenPath = path.join(environment.stateDir, "cloud-auth-token.json");
|
||||
|
||||
return DesktopCloudAuthTokenStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, tokenPath);
|
||||
if (Option.isNone(document) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(document.value.encryptedClientJwt);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}).pipe(Effect.withSpan("desktop.cloudAuthTokenStore.get")),
|
||||
set: Effect.fn("desktop.cloudAuthTokenStore.set")(function* (token) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedClientJwt = Encoding.encodeBase64(yield* safeStorage.encryptString(token));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
tokenPath,
|
||||
document: { version: 1, encryptedClientJwt },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopCloudAuthTokenStoreWriteError({ cause })));
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(tokenPath, { force: true }).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.withSpan("desktop.cloudAuthTokenStore.clear"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,415 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
|
||||
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
|
||||
decryptString: (value) => {
|
||||
return Effect.gen(function* () {
|
||||
const decoded = textDecoder.decode(value);
|
||||
if (
|
||||
!decoded.startsWith("encrypted:") ||
|
||||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
|
||||
) {
|
||||
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
|
||||
cause: new Error("invalid encrypted catalog"),
|
||||
});
|
||||
}
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
baseDir: string,
|
||||
encryptionAvailable = true,
|
||||
failDecrypt: Ref.Ref<boolean> | null = null,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
);
|
||||
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
|
||||
return DesktopConnectionCatalogStore.layer.pipe(
|
||||
Layer.provideMerge(savedEnvironmentsLayer),
|
||||
Layer.provideMerge(dependencies),
|
||||
);
|
||||
}
|
||||
|
||||
const withStore = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
|
||||
encryptionAvailable = true,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopConnectionCatalogStore", () => {
|
||||
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalog = '{"schemaVersion":1,"targets":[]}';
|
||||
|
||||
assert.isTrue(yield* store.set(catalog));
|
||||
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
|
||||
|
||||
yield* store.clear;
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist when secure storage is unavailable", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
assert.isFalse(yield* store.set("{}"));
|
||||
assert.deepStrictEqual(yield* store.get, Option.none());
|
||||
}),
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const records: readonly PersistedSavedEnvironmentRecord[] = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
httpBaseUrl: "https://relay.example.com/",
|
||||
wsBaseUrl: "wss://relay.example.com/",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
relayManaged: { relayUrl: "https://relay-control.example.com/" },
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
httpBaseUrl: "http://127.0.0.1:41773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:41773/",
|
||||
createdAt: "2026-06-02T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
createdAt: "2026-06-03T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
];
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
assert.isTrue(
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
secret: "legacy-token",
|
||||
}),
|
||||
);
|
||||
|
||||
const migrated = yield* store.get;
|
||||
assert.isTrue(Option.isSome(migrated));
|
||||
if (Option.isNone(migrated)) {
|
||||
return;
|
||||
}
|
||||
const catalog = yield* decodeConnectionCatalog(migrated.value);
|
||||
|
||||
assert.deepInclude(catalog.targets[0], {
|
||||
_tag: "RelayConnectionTarget",
|
||||
environmentId: EnvironmentId.make("relay-environment"),
|
||||
label: "Relay",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[1], {
|
||||
_tag: "SshConnectionTarget",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.targets[2], {
|
||||
_tag: "BearerConnectionTarget",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[0], {
|
||||
_tag: "SshConnectionProfile",
|
||||
connectionId: "ssh:ssh-environment",
|
||||
environmentId: EnvironmentId.make("ssh-environment"),
|
||||
label: "SSH",
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
assert.deepInclude(catalog.profiles[1], {
|
||||
_tag: "BearerConnectionProfile",
|
||||
connectionId: "bearer:bearer-environment",
|
||||
environmentId: EnvironmentId.make("bearer-environment"),
|
||||
label: "Bearer",
|
||||
httpBaseUrl: "https://bearer.example.com/",
|
||||
wsBaseUrl: "wss://bearer.example.com/",
|
||||
});
|
||||
assert.equal(catalog.credentials.length, 1);
|
||||
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
|
||||
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
|
||||
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
|
||||
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
|
||||
}
|
||||
|
||||
yield* savedEnvironments.setRegistry([]);
|
||||
assert.deepEqual(yield* store.get, migrated);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces malformed catalog documents without deleting them", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
|
||||
);
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed catalog write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.set("{}").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the legacy migration stage", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
|
||||
);
|
||||
assert.equal(error.operation, "read-legacy-registry");
|
||||
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
|
||||
assert.instanceOf(
|
||||
error.cause,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const registryError =
|
||||
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
assert.exists(registryError.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, registryError.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid encrypted catalog data without exposing it", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
|
||||
);
|
||||
assert.equal(error.resource, "encryptedCatalog");
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const failDecrypt = yield* Ref.make(false);
|
||||
const layer = makeLayer(baseDir, true, failDecrypt);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import {
|
||||
BearerConnectionCredential,
|
||||
BearerConnectionProfile,
|
||||
BearerConnectionTarget,
|
||||
RelayConnectionTarget,
|
||||
SshConnectionProfile,
|
||||
SshConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
|
||||
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const EncryptedConnectionCatalogDocument = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
encryptedCatalog: Schema.String,
|
||||
});
|
||||
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
|
||||
|
||||
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
|
||||
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
EncryptedConnectionCatalogDocumentJson,
|
||||
);
|
||||
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
|
||||
RuntimeConnectionCatalogDocument,
|
||||
);
|
||||
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
"read-legacy-secret",
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
resource: Schema.Literal("encryptedCatalog"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDocumentDecodeError",
|
||||
{
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: Schema.String,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
|
||||
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
|
||||
"DesktopConnectionCatalogStoreProtectionError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreProtectionOperation,
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
{
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
catalogPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDecodeError({
|
||||
resource: "encryptedCatalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const readDocument = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopConnectionCatalogStoreReadError({
|
||||
catalogPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDocumentDecodeError({
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "replace-catalog-file",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not remove a temporary connection catalog file.", {
|
||||
tempPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
|
||||
return `${prefix}:${environmentId}`;
|
||||
}
|
||||
|
||||
const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
|
||||
catalogPath: string,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopConnectionCatalogStoreMigrationError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (record.relayManaged !== undefined) {
|
||||
targets.push(
|
||||
new RelayConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (record.desktopSsh !== undefined) {
|
||||
const id = connectionId("ssh", record.environmentId);
|
||||
targets.push(
|
||||
new SshConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new SshConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
target: record.desktopSsh,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = connectionId("bearer", record.environmentId);
|
||||
targets.push(
|
||||
new BearerConnectionTarget({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
connectionId: id,
|
||||
}),
|
||||
);
|
||||
profiles.push(
|
||||
new BearerConnectionProfile({
|
||||
connectionId: id,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-secret",
|
||||
catalogPath,
|
||||
environmentId: record.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
credential: new BearerConnectionCredential({ token: token.value }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
targets,
|
||||
profiles,
|
||||
credentials,
|
||||
remoteDpopTokens: [],
|
||||
};
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "encrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
});
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-registry",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap((encryptedCatalog) =>
|
||||
safeStorage.decryptString(encryptedCatalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "decrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
|
||||
@@ -0,0 +1,37 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
|
||||
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
|
||||
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
|
||||
|
||||
describe("desktop detached action errors", () => {
|
||||
it("preserves the complete relaunch failure cause and reason", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("shutdown failed")),
|
||||
Cause.die(new Error("relaunch defect")),
|
||||
);
|
||||
const error = new DesktopLifecycleRelaunchError({
|
||||
reason: "apply update",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "apply update");
|
||||
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
|
||||
});
|
||||
|
||||
it("preserves the complete menu action failure cause and action", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("window unavailable")),
|
||||
Cause.die(new Error("dispatch defect")),
|
||||
);
|
||||
const error = new DesktopApplicationMenuActionError({
|
||||
action: "open-settings",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.action, "open-settings");
|
||||
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
|
||||
});
|
||||
});
|
||||
@@ -53,12 +53,16 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, true);
|
||||
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
|
||||
assert.equal(environment.baseDir, "/tmp/t3");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/dev");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
|
||||
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
|
||||
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
|
||||
assert.equal(
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
"/tmp/t3/userdata/saved-environments.json",
|
||||
);
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
@@ -77,7 +81,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
it.effect("stores production state under userdata in an explicit home", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -89,10 +93,24 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps implicit development state separate from production state", () =>
|
||||
Effect.gen(function* () {
|
||||
const development = yield* makeEnvironment(
|
||||
{},
|
||||
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
|
||||
);
|
||||
const production = yield* makeEnvironment();
|
||||
|
||||
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
|
||||
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses a configured app user model id override", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
|
||||
@@ -11,10 +11,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import {
|
||||
type DesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
} from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
@@ -30,54 +27,53 @@ export interface MakeDesktopEnvironmentInput {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopEnvironmentShape {
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
|
||||
export class DesktopEnvironment extends Context.Service<
|
||||
DesktopEnvironment,
|
||||
DesktopEnvironmentShape
|
||||
{
|
||||
readonly path: Path.Path;
|
||||
readonly dirname: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly processArch: string;
|
||||
readonly isPackaged: boolean;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
readonly appPath: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly homeDirectory: string;
|
||||
readonly appDataDirectory: string;
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: string;
|
||||
readonly desktopSettingsPath: string;
|
||||
readonly clientSettingsPath: string;
|
||||
readonly savedEnvironmentRegistryPath: string;
|
||||
readonly serverSettingsPath: string;
|
||||
readonly logDir: string;
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
readonly appUpdateYmlPath: string;
|
||||
readonly devServerUrl: Option.Option<URL>;
|
||||
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
|
||||
readonly configuredBackendPort: Option.Option<number>;
|
||||
readonly commitHashOverride: Option.Option<string>;
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly branding: DesktopAppBranding;
|
||||
readonly displayName: string;
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
@@ -135,9 +131,9 @@ function resolveDesktopRuntimeInfo(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
const make = Effect.fn("desktop.environment.make")(function* (
|
||||
input: MakeDesktopEnvironmentInput,
|
||||
): Effect.fn.Return<DesktopEnvironmentShape, Config.ConfigError, Path.Path> {
|
||||
): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const homeDirectory = input.homeDirectory;
|
||||
@@ -151,7 +147,8 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -159,7 +156,10 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const stateDir = path.join(
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
@@ -183,6 +183,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
|
||||
serverSettingsPath: path.join(stateDir, "settings.json"),
|
||||
logDir: path.join(stateDir, "logs"),
|
||||
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
|
||||
rootDir,
|
||||
appRoot,
|
||||
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
|
||||
@@ -206,7 +207,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: resolveDefaultDesktopSettings(input.appVersion),
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
runtimeInfo: resolveDesktopRuntimeInfo({
|
||||
platform: input.platform,
|
||||
processArch: input.processArch,
|
||||
@@ -248,4 +249,4 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
|
||||
});
|
||||
|
||||
export const layer = (input: MakeDesktopEnvironmentInput) =>
|
||||
Layer.effect(DesktopEnvironment, makeDesktopEnvironment(input));
|
||||
Layer.effect(DesktopEnvironment, make(input));
|
||||
@@ -1,75 +1,55 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
export interface DesktopShutdownShape {
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
|
||||
"DesktopLifecycleRelaunchError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop relaunch failed for reason "${this.reason}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
|
||||
) {}
|
||||
|
||||
const makeShutdown = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layerShutdown = Layer.effect(DesktopShutdown, makeShutdown);
|
||||
|
||||
export type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdown
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| DesktopWindow.DesktopWindow
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronTheme.ElectronTheme;
|
||||
|
||||
export interface DesktopLifecycleShape {
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
|
||||
*/
|
||||
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
) {}
|
||||
export class DesktopLifecycle extends Context.Service<
|
||||
DesktopLifecycle,
|
||||
{
|
||||
readonly relaunch: (
|
||||
reason: string,
|
||||
) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLifecycle") {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-lifecycle");
|
||||
makeComponentLogger("desktop-lifecycle");
|
||||
|
||||
function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
target: unknown,
|
||||
@@ -93,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown;
|
||||
function* (): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
|
||||
> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.flushMainWindowBounds;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
@@ -154,83 +140,81 @@ function quitFromSignal(
|
||||
);
|
||||
}
|
||||
|
||||
export const layer = Layer.succeed(
|
||||
DesktopLifecycle,
|
||||
DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
}
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
logLifecycleError("desktop relaunch failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
export const make = DesktopLifecycle.of({
|
||||
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
yield* logLifecycleInfo("desktop relaunch requested", { reason });
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(state.quitting, true);
|
||||
yield* requestDesktopShutdownAndWait();
|
||||
if (environment.isDevelopment) {
|
||||
yield* electronApp.exit(75);
|
||||
return;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
yield* electronApp.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
yield* electronApp.exit(0);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
const error = new DesktopLifecycleRelaunchError({ reason, cause });
|
||||
return logLifecycleError(error.message, { error });
|
||||
}),
|
||||
Effect.forkDetach,
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
);
|
||||
register: Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const context = yield* Effect.context<DesktopLifecycleRuntimeServices>();
|
||||
const runEffect = Effect.runPromiseWith(context);
|
||||
let quitAllowed = false;
|
||||
yield* electronTheme.onUpdated(() => {
|
||||
void runEffect(
|
||||
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("before-quit", (event: Electron.Event) => {
|
||||
handleBeforeQuit(
|
||||
event,
|
||||
runEffect,
|
||||
() => quitAllowed,
|
||||
() => {
|
||||
quitAllowed = true;
|
||||
},
|
||||
);
|
||||
});
|
||||
yield* electronApp.on("activate", () => {
|
||||
void runEffect(desktopWindow.activate.pipe(Effect.withSpan("desktop.lifecycle.activate")));
|
||||
});
|
||||
yield* electronApp.on("window-all-closed", () => {
|
||||
void runEffect(
|
||||
Effect.gen(function* () {
|
||||
const app = yield* ElectronApp.ElectronApp;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
|
||||
yield* app.quit;
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
|
||||
);
|
||||
});
|
||||
|
||||
if (environment.platform !== "win32") {
|
||||
yield* addScopedListener(process, "SIGINT", () => {
|
||||
quitFromSignal("SIGINT", runEffect);
|
||||
});
|
||||
yield* addScopedListener(process, "SIGTERM", () => {
|
||||
quitFromSignal("SIGTERM", runEffect);
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopLifecycle, make);
|
||||
@@ -125,7 +125,8 @@ describe("DesktopObservability", () => {
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
@@ -145,6 +146,7 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
@@ -152,6 +154,7 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.level, "INFO");
|
||||
assert.equal(output.annotations.component, "desktop-backend-child");
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
}).pipe(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -13,7 +13,9 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
@@ -40,10 +42,21 @@ export interface DesktopBackendOutputLogShape {
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
DesktopBackendOutputLogShape
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
// a writer that targets a distinct rotating log file — the primary
|
||||
// instance keeps `server-child.log` so the historical path stays stable
|
||||
// for ops; other instances get `server-child-<sanitized-id>.log`.
|
||||
//
|
||||
// Writers are cached per id within a single factory instance so repeated
|
||||
// `forInstance` calls (e.g. during a backend restart that re-resolves
|
||||
// services) reuse the same rotating writer rather than racing each other
|
||||
// on the same file.
|
||||
export class DesktopBackendOutputLogFactory extends Context.Service<
|
||||
DesktopBackendOutputLogFactory,
|
||||
{
|
||||
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
@@ -82,12 +95,13 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
|
||||
};
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
)<{
|
||||
readonly option: "maxBytes" | "maxFiles";
|
||||
readonly value: number;
|
||||
}> {
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
@@ -293,22 +307,51 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
|
||||
},
|
||||
);
|
||||
|
||||
const backendOutputLogLayer = Layer.effect(
|
||||
DesktopBackendOutputLog,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
|
||||
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
||||
|
||||
return Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn(
|
||||
"desktop.observability.backendOutput.writeSessionBoundary",
|
||||
)(function* ({ phase, details }) {
|
||||
const backendLogFilePathForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): string => {
|
||||
// Primary keeps the historical "server-child.log" path so ops scripts
|
||||
// and packaged-build log inspection still find it where it always lived.
|
||||
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}
|
||||
const sanitized = sanitizeInstanceIdForFileName(id);
|
||||
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
|
||||
};
|
||||
|
||||
// Just the IO sink. Cacheable by resolved file path so two ids that
|
||||
// sanitize to the same filename share a single RotatingLogFileWriter
|
||||
// (no race on currentSize tracking). Splitting the sink off from the
|
||||
// per-call shape lets the shape annotate writes with the *caller's*
|
||||
// id rather than whatever id created the cached writer first.
|
||||
const makeBackendOutputSinkForInstance = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<RotatingLogFileWriter>,
|
||||
never,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope
|
||||
> =>
|
||||
makeRotatingLogFileWriter({
|
||||
filePath: backendLogFilePathForInstance(environment, id),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
@@ -316,30 +359,81 @@ const backendOutputLogLayer = Layer.effect(
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
DesktopBackendOutputLogFactory,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const factoryScope = yield* Scope.Scope;
|
||||
// Per-file-path cache of the IO sink only. The per-call shape
|
||||
// wraps the sink with the caller's instance id so a cache hit on
|
||||
// a path collision (e.g. "wsl:default" and "wsl_default" both
|
||||
// resolve to server-child-wsl_default.log) doesn't attribute the
|
||||
// second caller's writes to the first caller's id. Each sink pins
|
||||
// itself to the factory's scope so all log resources tear down
|
||||
// together at app exit. Mutex serializes concurrent first-time
|
||||
// lookups for the same file path.
|
||||
const cacheRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
|
||||
>(new Map());
|
||||
|
||||
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Scope.provide(factoryScope),
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
}),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopBackendOutputLogFactory.of({
|
||||
forInstance: (id) => makeForId(id),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -387,7 +481,7 @@ const tracerLayer = Layer.unwrap(
|
||||
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
|
||||
|
||||
export const layer = Layer.mergeAll(
|
||||
backendOutputLogLayer,
|
||||
backendOutputLogFactoryLayer,
|
||||
desktopLoggerLayer,
|
||||
tracerLayer,
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export class DesktopShutdown extends Context.Service<
|
||||
DesktopShutdown,
|
||||
{
|
||||
readonly request: Effect.Effect<void>;
|
||||
readonly awaitRequest: Effect.Effect<void>;
|
||||
readonly markComplete: Effect.Effect<void>;
|
||||
readonly awaitComplete: Effect.Effect<void>;
|
||||
readonly isComplete: Effect.Effect<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopShutdown") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<void>();
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const completedRef = yield* Ref.make(false);
|
||||
|
||||
return DesktopShutdown.of({
|
||||
request: Deferred.succeed(requested, undefined).pipe(Effect.asVoid),
|
||||
awaitRequest: Deferred.await(requested),
|
||||
markComplete: Ref.set(completedRef, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(completed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
awaitComplete: Deferred.await(completed),
|
||||
isComplete: Ref.get(completedRef),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopShutdown, make);
|
||||
@@ -3,19 +3,17 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
export interface DesktopStateShape {
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
|
||||
"@t3tools/desktop/app/DesktopState",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
export class DesktopState extends Context.Service<
|
||||
DesktopState,
|
||||
Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
}),
|
||||
);
|
||||
{
|
||||
readonly backendReady: Ref.Ref<boolean>;
|
||||
readonly quitting: Ref.Ref<boolean>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopState") {}
|
||||
|
||||
const make = Effect.all({
|
||||
backendReady: Ref.make(false),
|
||||
quitting: Ref.make(false),
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopState, make);
|
||||
@@ -3,12 +3,20 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -21,6 +29,10 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
|
||||
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
|
||||
);
|
||||
|
||||
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
|
||||
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
|
||||
);
|
||||
|
||||
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
backendConfig: Effect.succeed({
|
||||
@@ -34,24 +46,27 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
platform: options?.platform ?? "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
appPath: options?.appPath ?? "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: "/missing/resources",
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -69,6 +84,14 @@ function makeEnvironmentLayer(
|
||||
);
|
||||
}
|
||||
|
||||
const restoreEnv = (name: string, value: string | undefined) => {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
};
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
@@ -89,6 +112,8 @@ const withHarness = <A, E, R>(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -96,14 +121,14 @@ const withHarness = <A, E, R>(
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
|
||||
|
||||
describe("DesktopBackendConfiguration", () => {
|
||||
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
|
||||
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const first = yield* configuration.resolve;
|
||||
const second = yield* configuration.resolve;
|
||||
const first = yield* configuration.resolvePrimary;
|
||||
const second = yield* configuration.resolvePrimary;
|
||||
|
||||
assert.equal(first.executablePath, process.execPath);
|
||||
assert.equal(first.entryPath, environment.backendEntryPath);
|
||||
@@ -127,7 +152,167 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes persisted backend observability endpoints when present", () =>
|
||||
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
const primary = yield* configuration.resolvePrimary;
|
||||
const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const observedDistros: Array<string | null> = [];
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: null });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
],
|
||||
windowsToWslPath: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("/repo/apps/server/dist/bin.mjs");
|
||||
},
|
||||
ensureNodePty: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
|
||||
},
|
||||
getDistroIp: (distro) => {
|
||||
observedDistros.push(distro);
|
||||
return Option.some("172.27.0.99");
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.runningDistro, "Ubuntu");
|
||||
assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
|
||||
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
|
||||
const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
windowsToWslPath: () => Option.some(linuxEntryPath),
|
||||
ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: baseDir,
|
||||
devServerUrl,
|
||||
isPackaged: true,
|
||||
platform: "win32",
|
||||
resourcesPath: baseDir,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.bootstrapDelivery, "stdin");
|
||||
assert.deepEqual(config.args, [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--exec",
|
||||
"env",
|
||||
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
|
||||
nodePath,
|
||||
linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
"--dev-url",
|
||||
devServerUrl,
|
||||
]);
|
||||
assert.notInclude(config.args, "bash");
|
||||
assert.notInclude(config.args, "/bin/sh");
|
||||
assert.notInclude(config.args, "-c");
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
|
||||
// Resolve both before any token is cached, concurrently, so the
|
||||
// generate step (a yield point) can interleave. The atomic
|
||||
// get-or-create must still hand both the same token; a non-atomic
|
||||
// Ref would let each generate its own and break the shared-token
|
||||
// invariant.
|
||||
const [primary, wsl] = yield* Effect.all(
|
||||
[configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -147,18 +332,18 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* configuration.resolve;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
|
||||
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits backend observability endpoints when settings are missing", () =>
|
||||
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
@@ -166,7 +351,66 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("captures backend output in development so child process logs can be persisted", () =>
|
||||
it.effect("logs structured context when persisted observability settings cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: settingsPath,
|
||||
});
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
const failingFileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolvePrimary;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isUndefined(config.bootstrap.otlpTracesUrl);
|
||||
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
|
||||
|
||||
const error = messages
|
||||
.flatMap((message) => (Array.isArray(message) ? message : [message]))
|
||||
.find(isDesktopBackendObservabilitySettingsReadError);
|
||||
assert.isDefined(error);
|
||||
assert.equal(error.settingsPath, settingsPath);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read persisted backend observability settings at ${settingsPath}.`,
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
@@ -175,12 +419,14 @@ describe("DesktopBackendConfiguration", () => {
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
assert.equal(config.captureOutput, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
isPackaged: false,
|
||||
@@ -192,4 +438,362 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
const previousWslEnv = process.env.WSLENV;
|
||||
const previousOpenAiKey = process.env.OPENAI_API_KEY;
|
||||
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
|
||||
try {
|
||||
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
|
||||
process.env.OPENAI_API_KEY = "openai-key";
|
||||
process.env.ANTHROPIC_API_KEY = "anthropic-key";
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.equal(config.bootstrap.port, 5050);
|
||||
// Binds to 0.0.0.0 inside WSL so the backend is reachable via
|
||||
// both wslhost-forwarded localhost and the distro's eth0 IP.
|
||||
assert.equal(config.bootstrap.host, "0.0.0.0");
|
||||
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
|
||||
// httpBaseUrl uses the resolved distro IP from the test stub,
|
||||
// not localhost — the renderer reaches the backend directly to
|
||||
// avoid relying on wslhost forwarding.
|
||||
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
|
||||
assert.equal(config.env.OPENAI_API_KEY, "openai-key");
|
||||
assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
|
||||
// The existing WSLENV is preserved byte-for-byte (note the empty
|
||||
// "::" segment survives — WSL ignores it, so we don't normalize
|
||||
// it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
|
||||
// already declared, so it isn't forwarded twice.
|
||||
assert.equal(
|
||||
config.env.WSLENV,
|
||||
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
|
||||
getDistroIp: () => Option.some("172.27.0.99"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
restoreEnv("WSLENV", previousWslEnv);
|
||||
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
|
||||
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
|
||||
}
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
|
||||
// wsl-only is persisted but WSL is unavailable, so the primary must
|
||||
// not spawn wsl.exe (which would loop on preflight failures while the
|
||||
// Connections backend control is hidden). Resolve the Windows primary.
|
||||
assert.equal(config.executablePath, process.execPath);
|
||||
assert.equal(config.bootstrap.t3Home, environment.baseDir);
|
||||
assert.isTrue(Option.isNone(config.preflightFailure));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.equal(config.executablePath, "wsl.exe");
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Removed-Distro",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isFalse(failure.fatal);
|
||||
assert.equal(failure.retryLimit, 12);
|
||||
assert.include(failure.reason, "timed out");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
|
||||
reason: "wsl.exe --list --verbose timed out",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "missing server entry");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isTrue(failure.fatal);
|
||||
assert.include(failure.reason, "Removed-Distro");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "WSL (Ubuntu)");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Local environment");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
// Mirrors the resolvePrimary fall-back: the label must follow the
|
||||
// backend that actually resolves, not the persisted preference, so the
|
||||
// env switcher can't show "WSL" for a Windows backend.
|
||||
const label = yield* configuration.resolvePrimaryLabel;
|
||||
assert.equal(label, "Windows");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopAppSettings.layerTest({
|
||||
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
wslBackendEnabled: true,
|
||||
wslOnly: true,
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
|
||||
// getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
|
||||
// primary instance's lazy label through Effect.runSync. The label chains
|
||||
// to wslEnvironment.isAvailable, whose real layer probes the filesystem.
|
||||
// That probe must run once at layer build and expose a resolved value, not
|
||||
// a live async effect — otherwise runSync throws in the handler. Build the
|
||||
// real WSL layer (not the sync test stub) and resolve the label with a
|
||||
// top-level runSync, exactly as the handler does.
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
|
||||
const runtime = ManagedRuntime.make(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
// isAvailable on win32 only touches the filesystem, never the spawner,
|
||||
// so a die-stub is enough to satisfy the layer's deps.
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.die("spawner should not be used while probing WSL availability"),
|
||||
),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const configuration = await runtime.runPromise(
|
||||
DesktopBackendConfiguration.DesktopBackendConfiguration,
|
||||
);
|
||||
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
|
||||
const label = Effect.runSync(configuration.resolvePrimaryLabel);
|
||||
assert.equal(typeof label, "string");
|
||||
} finally {
|
||||
await runtime.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -7,23 +9,58 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import serverPackageJson from "../../../server/package.json" with { type: "json" };
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
{
|
||||
settingsPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
{
|
||||
// Build the Windows-native primary backend's start config. Reads the
|
||||
// primary's port/host/exposure from DesktopServerExposure. Can fail
|
||||
// with PlatformError because bootstrap token generation now uses
|
||||
// crypto.randomBytes under the hood (post Effect 4 migration).
|
||||
readonly resolvePrimary: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// Build a WSL backend start config for the given distro on the given
|
||||
// port. The WSL backend is always loopback-only (the primary owns LAN
|
||||
// exposure when the user opts in), so this takes the port directly and
|
||||
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
|
||||
// forwarded to wsl.exe with no -d flag.
|
||||
readonly resolveWsl: (input: {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
}) => Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
// The renderer-facing label for the primary instance, derived from the
|
||||
// same decision resolvePrimary makes (including the WSL-availability
|
||||
// fall-back to Windows), so the env switcher can't show "WSL" for a
|
||||
// backend that actually resolved to Windows.
|
||||
readonly resolvePrimaryLabel: Effect.Effect<string>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
@@ -49,32 +86,76 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
"T3CODE_TAILSCALE_SERVE_PORT",
|
||||
] as const;
|
||||
|
||||
// Sensitive env vars that the WSL backend needs but Windows process.env won't
|
||||
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
|
||||
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
|
||||
// URL-shaped values (colons / slashes) is unreliable.
|
||||
const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
|
||||
|
||||
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
||||
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
|
||||
"desktop-backend-configuration",
|
||||
);
|
||||
const getWslEnvEntryName = (entry: string): string => {
|
||||
const slashIndex = entry.indexOf("/");
|
||||
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
|
||||
};
|
||||
|
||||
const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
BackendObservabilitySettings,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const mergeWslEnv = (
|
||||
existingWslEnv: string | undefined,
|
||||
forwardedEnvNames: ReadonlyArray<string>,
|
||||
): string | undefined => {
|
||||
const existing = existingWslEnv?.trim() ?? "";
|
||||
|
||||
// Names already declared, so we don't forward a duplicate. We parse the
|
||||
// existing value only for this membership test — the string itself is
|
||||
// preserved verbatim below rather than re-serialized.
|
||||
const seenNames = new Set(
|
||||
existing
|
||||
.split(":")
|
||||
.map((entry) => getWslEnvEntryName(entry.trim()))
|
||||
.filter((name) => name.length > 0),
|
||||
);
|
||||
|
||||
const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
|
||||
|
||||
// Preserve the user's WSLENV exactly as Windows handed it to us — empty
|
||||
// "::" segments and duplicate entries are harmless no-ops to WSL and not
|
||||
// ours to normalize — and only append the secrets we need to forward
|
||||
// across the wsl.exe boundary.
|
||||
const parts = [existing, ...additions].filter((part) => part.length > 0);
|
||||
return parts.length > 0 ? parts.join(":") : undefined;
|
||||
};
|
||||
|
||||
const logBackendObservabilitySettingsReadFailure = (
|
||||
settingsPath: string,
|
||||
cause: PlatformError.PlatformError,
|
||||
) => {
|
||||
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
|
||||
return Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
component: "desktop-backend-configuration",
|
||||
error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const exists = yield* fileSystem
|
||||
.exists(environment.serverSettingsPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
|
||||
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
|
||||
Effect.as(Option.none()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (Option.isNone(raw)) {
|
||||
yield* logBackendConfigurationWarning(
|
||||
"failed to read persisted backend observability settings",
|
||||
);
|
||||
return emptyBackendObservabilitySettings;
|
||||
}
|
||||
|
||||
@@ -85,11 +166,168 @@ const readPersistedBackendObservabilitySettings: Effect.Effect<
|
||||
};
|
||||
});
|
||||
|
||||
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}): Effect.fn.Return<
|
||||
interface SharedBootstrapInput {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}
|
||||
|
||||
interface WslPreflightSuccess {
|
||||
readonly _tag: "Ready";
|
||||
readonly runningDistro: string;
|
||||
readonly linuxEntryPath: string;
|
||||
// Absolute path to the node binary the preflight validated after the shared
|
||||
// remote resolver repaired PATH. The launch must use this exact path so it
|
||||
// doesn't fall through to a different/old node than the one node-pty was
|
||||
// built against.
|
||||
readonly nodePath: string;
|
||||
// PATH captured from the same login shell after the shared resolver loaded
|
||||
// version managers. The launch forwards this value directly without a shell.
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
|
||||
interface WslPreflightFailure {
|
||||
readonly _tag: "Failed";
|
||||
readonly reason: string;
|
||||
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
|
||||
// build tools) and retrying won't help — surface it and (wsl-only) fall back
|
||||
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
|
||||
// boots), with a bounded window for self-healing before fallback.
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
}
|
||||
|
||||
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
|
||||
|
||||
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
readonly windowsEntryPath: string;
|
||||
readonly windowsRepoRoot: string;
|
||||
readonly allowBuild: boolean;
|
||||
}): Effect.fn.Return<
|
||||
WslPreflightSuccess | WslPreflightFailure,
|
||||
never,
|
||||
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
|
||||
> {
|
||||
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const wslAvailable = yield* wslEnv.isAvailable;
|
||||
if (!wslAvailable) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: "WSL is not available on this system",
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const distroProbe = yield* wslEnv.probeDistros.pipe(
|
||||
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
|
||||
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
|
||||
);
|
||||
if (distroProbe._tag === "Failure") {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const installedDistros = distroProbe.distros;
|
||||
const runningDistro = input.distro
|
||||
? (installedDistros.find(
|
||||
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
|
||||
)?.name ?? null)
|
||||
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
|
||||
if (runningDistro === null) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: input.distro
|
||||
? `WSL distro is not installed: ${input.distro}`
|
||||
: installedDistros.length === 0
|
||||
? "WSL has no installed distributions"
|
||||
: "WSL has no default distribution",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(input.windowsEntryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!entryExists) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `missing server entry at ${input.windowsEntryPath}`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
|
||||
if (Option.isNone(linuxEntry)) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
|
||||
fatal: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
|
||||
allowBuild: input.allowBuild,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
});
|
||||
if (!nodePtyResult.ok) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
|
||||
fatal: nodePtyResult.fatal,
|
||||
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
_tag: "Ready",
|
||||
runningDistro,
|
||||
linuxEntryPath: linuxEntry.value,
|
||||
nodePath: nodePtyResult.nodePath,
|
||||
resolvedPath: nodePtyResult.resolvedPath,
|
||||
} as const;
|
||||
});
|
||||
|
||||
// True when the given IPv4 belongs to a Windows-side network
|
||||
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
|
||||
// host's, which is the signature we use to detect that mode and
|
||||
// switch the renderer URL to loopback.
|
||||
const isLocalHostIpv4 = (ip: string): boolean => {
|
||||
const interfaces = NodeOS.networkInterfaces();
|
||||
for (const list of Object.values(interfaces)) {
|
||||
if (!list) continue;
|
||||
for (const entry of list) {
|
||||
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
|
||||
// the Node build Electron ships (41 / Node 22, verified), but some Node
|
||||
// builds report the numeric 4. Normalize to a string so a future runtime
|
||||
// bump can't silently break mirrored-mode detection and leave the
|
||||
// renderer pointed at the distro IP instead of loopback.
|
||||
const family = String(entry.family);
|
||||
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
|
||||
...Option.match(observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
});
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
@@ -98,72 +336,351 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
},
|
||||
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
|
||||
extendEnv: true,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "fd3",
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
};
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
},
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendConfiguration,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
|
||||
input: SharedBootstrapInput & {
|
||||
readonly port: number;
|
||||
readonly distro: string | null;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
|
||||
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
|
||||
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
|
||||
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
|
||||
// Windows. wslhost forwarding is unreliable on some Windows hosts:
|
||||
// the desktop's readiness probe and the renderer's saved-env-style
|
||||
// fetch both saw "Failed to fetch" when the backend only bound to
|
||||
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
|
||||
// WSL IP as the renderer-visible URL avoids that dependency.
|
||||
// Security-wise this is acceptable for the local-only WSL backend:
|
||||
// the network it exposes on is the WSL-vEthernet network, not the
|
||||
// LAN; the primary owns LAN exposure when the user opts in.
|
||||
const wslBindHost = "0.0.0.0";
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: input.port,
|
||||
// Omit t3Home so the Linux backend uses its own home dir instead of
|
||||
// the Windows-side baseDir (which would be a /mnt/c path and share
|
||||
// the SQLite file with the primary).
|
||||
host: wslBindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
// PortSchema rejects 0, so when tailscale serve is disabled we still
|
||||
// need a valid number in this slot. The backend reads tailscaleServePort
|
||||
// only when tailscaleServeEnabled is true, so the actual value here is
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
// In packaged builds environment.appRoot is .../resources/app.asar — an
|
||||
// archive FILE. The Windows primary reads its entry through
|
||||
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
|
||||
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
|
||||
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
|
||||
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
|
||||
// already a real directory, so this is a no-op.
|
||||
const wslAppRoot = environment.isPackaged
|
||||
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
|
||||
: environment.appRoot;
|
||||
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
|
||||
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
// changes between probing and spawning the backend.
|
||||
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
|
||||
const distroForConfig = runningDistro ?? input.distro;
|
||||
|
||||
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
|
||||
// reports a host interface, so use loopback instead; a failed probe also
|
||||
// falls back to loopback and preserves the previous behavior.
|
||||
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
|
||||
const usesSharedNetworkStack = Option.match(distroIp, {
|
||||
onNone: () => false,
|
||||
onSome: (ip) => isLocalHostIpv4(ip),
|
||||
});
|
||||
const rendererHost = usesSharedNetworkStack
|
||||
? "127.0.0.1"
|
||||
: Option.getOrElse(distroIp, () => "127.0.0.1");
|
||||
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
|
||||
|
||||
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
|
||||
const forwardedEnv: Record<string, string> = {};
|
||||
const forwardedEnvNames: string[] = [];
|
||||
for (const name of WSL_FORWARDED_ENV_NAMES) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined && value.length > 0) {
|
||||
forwardedEnv[name] = value;
|
||||
forwardedEnvNames.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
|
||||
// exports the Windows-side base dir for the primary; if it leaks into
|
||||
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
|
||||
// /mnt/c, which means both backends read/write the same database and
|
||||
// their env-ids collide).
|
||||
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "T3CODE_HOME") continue;
|
||||
parentEnvWithoutT3Home[key] = value;
|
||||
}
|
||||
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
|
||||
|
||||
const baseConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
entryPath: wslEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...parentEnvWithoutT3Home,
|
||||
...backendChildEnvPatch(),
|
||||
...forwardedEnv,
|
||||
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
|
||||
},
|
||||
// env is already a complete process.env minus T3CODE_HOME; pass it
|
||||
// verbatim instead of letting the spawner re-merge process.env on top.
|
||||
extendEnv: false,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "stdin" as const,
|
||||
httpBaseUrl,
|
||||
captureOutput: true,
|
||||
...(runningDistro !== null ? { runningDistro } : {}),
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
const devUrlArgs = Option.match(environment.devServerUrl, {
|
||||
onNone: () => [] as ReadonlyArray<string>,
|
||||
onSome: (url) => ["--dev-url", url.href],
|
||||
});
|
||||
|
||||
if (preflight._tag === "Failed") {
|
||||
const retryLimit =
|
||||
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [...distroArgs, "--", "node", "--version"],
|
||||
preflightFailure: Option.some({
|
||||
reason: preflight.reason,
|
||||
fatal: preflight.fatal,
|
||||
...(retryLimit === undefined ? {} : { retryLimit }),
|
||||
}),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
|
||||
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
|
||||
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
|
||||
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
|
||||
// user PATH entries captured by the login-shell preflight. Every dynamic
|
||||
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
|
||||
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
|
||||
// for the bootstrap envelope.
|
||||
const lastSlash = preflight.nodePath.lastIndexOf("/");
|
||||
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
|
||||
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
|
||||
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [
|
||||
...distroArgs,
|
||||
"--exec",
|
||||
"env",
|
||||
`PATH=${launchPath}`,
|
||||
preflight.nodePath,
|
||||
preflight.linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
...devUrlArgs,
|
||||
],
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
|
||||
// resolve concurrently; with a plain Ref both could observe None, generate
|
||||
// distinct tokens, and one would overwrite the other — leaving the two
|
||||
// backends holding mismatched tokens and breaking the shared-token
|
||||
// invariant the renderer relies on. modifyEffect serializes the whole
|
||||
// get-or-create so the first caller wins and the rest reuse its token.
|
||||
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
|
||||
Option.match(current, {
|
||||
onSome: (token) => Effect.succeed([token, current] as const),
|
||||
onNone: () =>
|
||||
crypto.randomBytes(24).pipe(
|
||||
Effect.map((bytes) => {
|
||||
const token = Encoding.encodeHex(bytes);
|
||||
return [token, Option.some(token)] as const;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
// Both resolvers share the same bootstrap token: the renderer holds a
|
||||
// single token and uses it against whichever backend it's currently
|
||||
// talking to. Observability settings get re-read each resolve so a
|
||||
// hot-swap of the server-settings file is picked up on the next
|
||||
// restart cycle without having to bounce the desktop process.
|
||||
const sharedInputs = Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
|
||||
});
|
||||
|
||||
const buildWslPrimaryConfig = Effect.gen(function* () {
|
||||
// wsl-only mode pipes the WSL backend through the same port the
|
||||
// Windows primary would normally take. That way the renderer
|
||||
// still loads from the local-only endpoint advertised by
|
||||
// DesktopServerExposure, and primary-aware code paths (cookie
|
||||
// auth, the env switcher's "primary" id) keep working without
|
||||
// a parallel "secondary" registration.
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
const persistedSettings = yield* settings.get;
|
||||
const shared = yield* sharedInputs;
|
||||
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
|
||||
return yield* resolveWslStartConfig({
|
||||
...shared,
|
||||
port: backendExposure.port,
|
||||
distro: persistedSettings.wslDistro,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
});
|
||||
|
||||
// Single source of truth for what the primary actually runs as. Both
|
||||
// the start-config dispatch and the renderer-facing label derive from
|
||||
// this, so they can't disagree — e.g. the label reading "WSL" while the
|
||||
// config silently fell back to Windows because WSL is unavailable.
|
||||
// Dispatch happens at resolve time so toggling wsl-only between restarts
|
||||
// is picked up on the next start cycle (the pool's primary instance is
|
||||
// created once at layer init, but configResolve fires on each restart).
|
||||
const describePrimary = Effect.gen(function* () {
|
||||
const persistedSettings = yield* settings.get;
|
||||
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
|
||||
// Only honor wsl-only when WSL is actually usable. If the user
|
||||
// persisted wsl-only but WSL has since become unavailable (wsl.exe
|
||||
// removed, no distro), fall back to the Windows primary instead of
|
||||
// looping forever on preflight failures: the Connections backend
|
||||
// control is hidden while WSL is unavailable, so a stuck WSL primary
|
||||
// would otherwise leave no in-app way back to Windows.
|
||||
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
|
||||
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolvePrimary: Effect.gen(function* () {
|
||||
const { useWsl, wslRequested } = yield* describePrimary;
|
||||
if (useWsl) {
|
||||
return yield* buildWslPrimaryConfig;
|
||||
}
|
||||
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
if (wslRequested) {
|
||||
yield* Effect.logWarning(
|
||||
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
|
||||
);
|
||||
}
|
||||
return yield* buildWindowsPrimaryConfig;
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
|
||||
resolvePrimaryLabel: Effect.gen(function* () {
|
||||
const { useWsl, distro } = yield* describePrimary;
|
||||
if (!useWsl) {
|
||||
return environment.platform === "win32" ? "Windows" : "Local environment";
|
||||
}
|
||||
return distro ? `WSL (${distro})` : "WSL";
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
|
||||
resolveWsl: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
|
||||
attributes: { port: input.port, distro: input.distro ?? null },
|
||||
}),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendConfiguration, make);
|
||||
@@ -20,10 +20,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
@@ -31,6 +28,7 @@ const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: { ELECTRON_RUN_AS_NODE: "1" },
|
||||
@@ -44,8 +42,11 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
bootstrapDelivery: "fd3",
|
||||
extendEnv: true,
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
};
|
||||
|
||||
const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
@@ -101,97 +102,98 @@ function decodeBootstrap(raw: string) {
|
||||
return decodeDesktopBackendBootstrap(raw);
|
||||
}
|
||||
|
||||
function makeManagerLayer(input: {
|
||||
interface MakeInstanceInput {
|
||||
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
|
||||
readonly desktopState?: DesktopState.DesktopStateShape;
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
|
||||
readonly onReady?: Effect.Effect<void>;
|
||||
readonly onShutdown?: Effect.Effect<void>;
|
||||
readonly onPreflightFailed?: (
|
||||
failure: DesktopBackendManager.PreflightFailure,
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
FileSystem.layerNoop({
|
||||
exists: () => Effect.succeed(true),
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolve: Effect.succeed(input.config ?? baseConfig),
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
: DesktopState.layer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected createMain"),
|
||||
ensureMain: Effect.die("unexpected ensureMain"),
|
||||
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
|
||||
activate: Effect.void,
|
||||
createMainIfBackendReady: Effect.void,
|
||||
handleBackendReady: Effect.void,
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
...input.desktopWindow,
|
||||
} satisfies DesktopWindow.DesktopWindowShape),
|
||||
),
|
||||
),
|
||||
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
}
|
||||
|
||||
// Helper that constructs a primary backend instance using the factory
|
||||
// directly. The factory's deps (FileSystem, ChildProcessSpawner,
|
||||
// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
|
||||
// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
|
||||
// to drive the instance's lifecycle.
|
||||
function makeTestInstance(input: MakeInstanceInput) {
|
||||
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
...input.backendOutputLog,
|
||||
};
|
||||
const servicesLayer = Layer.mergeAll(
|
||||
FileSystem.layerNoop({
|
||||
exists: () => Effect.succeed(true),
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () => Effect.succeed(stubLog),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
);
|
||||
|
||||
const instance = DesktopBackendManager.makeBackendInstance({
|
||||
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
|
||||
...(input.onReady ? { onReady: () => input.onReady! } : {}),
|
||||
...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
|
||||
...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
|
||||
});
|
||||
|
||||
return instance.pipe(Effect.provide(servicesLayer));
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
let bootstrapJson = "";
|
||||
let readyCount = 0;
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
let bootstrapJson = "";
|
||||
let readyCount = 0;
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
spawnedCommand = command;
|
||||
if (command._tag === "StandardCommand") {
|
||||
const fd3 = command.options.additionalFds?.fd3;
|
||||
if (fd3?.type === "input" && fd3.stream) {
|
||||
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
Effect.gen(function* () {
|
||||
spawnedCommand = command;
|
||||
if (command._tag === "StandardCommand") {
|
||||
const fd3 = command.options.additionalFds?.fd3;
|
||||
if (fd3?.type === "input" && fd3.stream) {
|
||||
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
config: {
|
||||
...baseConfig,
|
||||
bootstrap: configWithObservability,
|
||||
},
|
||||
spawnerLayer,
|
||||
desktopWindow: {
|
||||
handleBackendReady: Effect.sync(() => {
|
||||
const instance = yield* makeTestInstance({
|
||||
config: {
|
||||
...baseConfig,
|
||||
bootstrap: configWithObservability,
|
||||
},
|
||||
spawnerLayer,
|
||||
onReady: Effect.sync(() => {
|
||||
readyCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
yield* Queue.take(exited);
|
||||
|
||||
assert.equal(readyCount, 1);
|
||||
@@ -214,55 +216,52 @@ describe("DesktopBackendManager", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
const statuses = [503, 200];
|
||||
let readyCount = 0;
|
||||
const firstRequest = yield* Deferred.make<void>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
const statuses = [503, 200];
|
||||
let readyCount = 0;
|
||||
const firstRequest = yield* Deferred.make<void>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer((request) =>
|
||||
Effect.gen(function* () {
|
||||
const status = statuses.shift();
|
||||
assert.isDefined(status);
|
||||
requestUrls.push(request.url);
|
||||
yield* Deferred.succeed(firstRequest, void 0);
|
||||
return responseForRequest(request, status);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer((request) =>
|
||||
Effect.gen(function* () {
|
||||
const status = statuses.shift();
|
||||
assert.isDefined(status);
|
||||
requestUrls.push(request.url);
|
||||
yield* Deferred.succeed(firstRequest, void 0);
|
||||
return responseForRequest(request, status);
|
||||
}),
|
||||
),
|
||||
desktopWindow: {
|
||||
handleBackendReady: Effect.sync(() => {
|
||||
onReady: Effect.sync(() => {
|
||||
readyCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
yield* Deferred.await(firstRequest);
|
||||
|
||||
assert.equal(readyCount, 0);
|
||||
@@ -276,106 +275,136 @@ describe("DesktopBackendManager", () => {
|
||||
"http://127.0.0.1:3773/.well-known/t3/environment",
|
||||
"http://127.0.0.1:3773/.well-known/t3/environment",
|
||||
]);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("starts the configured backend and closes the scoped process on stop", () =>
|
||||
Effect.gen(function* () {
|
||||
let startCount = 0;
|
||||
let closedCount = 0;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const startedPids = yield* Queue.unbounded<number>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReady = yield* Ref.make(false);
|
||||
const quitting = yield* Ref.make(false);
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let startCount = 0;
|
||||
let closedCount = 0;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const startedPids = yield* Queue.unbounded<number>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReadyFlag = yield* Ref.make(false);
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
startCount += 1;
|
||||
yield* Queue.offer(startedPids, 123);
|
||||
const close = Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
startCount += 1;
|
||||
yield* Queue.offer(startedPids, 123);
|
||||
const close = Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
|
||||
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
kill: () => close,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
kill: () => close,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopState: {
|
||||
backendReady,
|
||||
quitting,
|
||||
},
|
||||
desktopWindow: {
|
||||
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
onReady: Ref.set(backendReadyFlag, true).pipe(
|
||||
Effect.andThen(Deferred.succeed(ready, void 0)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
onShutdown: Ref.set(backendReadyFlag, false),
|
||||
});
|
||||
assert.isTrue(Option.isNone(yield* instance.currentConfig));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
assert.isTrue(Option.isNone(yield* manager.currentConfig));
|
||||
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(startedPids), 123);
|
||||
yield* Deferred.await(ready);
|
||||
assert.isTrue(yield* Ref.get(backendReady));
|
||||
assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
|
||||
assert.isTrue(yield* Ref.get(backendReadyFlag));
|
||||
assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
|
||||
|
||||
const runningSnapshot = yield* manager.snapshot;
|
||||
const runningSnapshot = yield* instance.snapshot;
|
||||
assert.equal(runningSnapshot.ready, true);
|
||||
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
|
||||
|
||||
yield* manager.stop();
|
||||
yield* instance.stop();
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
|
||||
const stoppedSnapshot = yield* manager.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReady));
|
||||
const stoppedSnapshot = yield* instance.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReadyFlag));
|
||||
assert.equal(stoppedSnapshot.desiredRunning, false);
|
||||
assert.equal(stoppedSnapshot.ready, false);
|
||||
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not notify shutdown before the first start has prior state", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let shutdownCount = 0;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const startedPids = yield* Queue.unbounded<number>();
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(startedPids, 123);
|
||||
const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
kill: () => close,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
onShutdown: Effect.sync(() => {
|
||||
shutdownCount += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(startedPids), 123);
|
||||
assert.equal(shutdownCount, 0);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
let startCount = 0;
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.sync(() => {
|
||||
startCount += 1;
|
||||
return makeProcess({
|
||||
exitCode: Queue.offer(starts, startCount).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(1)),
|
||||
),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.sync(() => {
|
||||
startCount += 1;
|
||||
return makeProcess({
|
||||
exitCode: Queue.offer(starts, startCount).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(1)),
|
||||
),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
@@ -388,107 +417,300 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(yield* Queue.take(starts), 3);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let shutdownCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
config: {
|
||||
...baseConfig,
|
||||
preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
|
||||
},
|
||||
onShutdown: Effect.sync(() => {
|
||||
shutdownCount += 1;
|
||||
}),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(shutdownCount, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
assert.equal(shutdownCount, 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const failures: string[] = [];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
config: {
|
||||
...baseConfig,
|
||||
preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
|
||||
},
|
||||
onPreflightFailed: (failure) =>
|
||||
Effect.sync(() => {
|
||||
failures.push(failure.reason);
|
||||
}).pipe(Effect.as(false)),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.deepEqual(failures, []);
|
||||
|
||||
// Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
|
||||
// the cap, at which point the failure is surfaced exactly once.
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
yield* TestClock.adjust(Duration.seconds(4));
|
||||
assert.deepEqual(failures, ["Node.js not found"]);
|
||||
|
||||
// Past the cap the loop stops and nothing else is surfaced.
|
||||
yield* TestClock.adjust(Duration.seconds(8));
|
||||
yield* TestClock.adjust(Duration.seconds(30));
|
||||
assert.deepEqual(failures, ["Node.js not found"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("can be started again after a fatal preflight cap once config recovers", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const failing = yield* Ref.make(true);
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Queue.offer(starts, 123).pipe(
|
||||
Effect.as(
|
||||
makeProcess({
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
configResolve: Ref.get(failing).pipe(
|
||||
Effect.map((isFailing) =>
|
||||
isFailing
|
||||
? {
|
||||
...baseConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "Node.js not found",
|
||||
fatal: true,
|
||||
}),
|
||||
}
|
||||
: baseConfig,
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
yield* TestClock.adjust(Duration.seconds(4));
|
||||
yield* TestClock.adjust(Duration.seconds(8));
|
||||
|
||||
const parked = yield* instance.snapshot;
|
||||
assert.equal(parked.desiredRunning, false);
|
||||
assert.equal(parked.ready, false);
|
||||
assert.isTrue(Option.isNone(parked.activePid));
|
||||
assert.equal(parked.restartScheduled, false);
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
|
||||
yield* Ref.set(failing, false);
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 123);
|
||||
const running = yield* instance.snapshot;
|
||||
assert.equal(running.desiredRunning, true);
|
||||
assert.deepEqual(running.activePid, Option.some(123));
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const failures: string[] = [];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
config: {
|
||||
...baseConfig,
|
||||
preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
|
||||
},
|
||||
onPreflightFailed: (failure) =>
|
||||
Effect.sync(() => {
|
||||
failures.push(failure.reason);
|
||||
}).pipe(Effect.as(false)),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
// Well beyond the fatal cap's worth of time: a transient failure must
|
||||
// keep retrying (self-heal) and never surface.
|
||||
yield* TestClock.adjust(Duration.minutes(2));
|
||||
assert.deepEqual(failures, []);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const failures: string[] = [];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
config: {
|
||||
...baseConfig,
|
||||
preflightFailure: Option.some({
|
||||
reason: "WSL toolchain probe timed out",
|
||||
fatal: false,
|
||||
retryLimit: 3,
|
||||
}),
|
||||
},
|
||||
onPreflightFailed: (failure) =>
|
||||
Effect.sync(() => {
|
||||
failures.push(failure.reason);
|
||||
}).pipe(Effect.as(false)),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
assert.deepEqual(failures, []);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("cancels a scheduled restart when start is requested manually", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const secondClosed = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const secondClosed = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
|
||||
if (startCount === 1) {
|
||||
if (startCount === 1) {
|
||||
return makeProcess({
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
});
|
||||
}
|
||||
|
||||
const scope = yield* Scope.Scope;
|
||||
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
return makeProcess({
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
exitCode: Deferred.await(secondClosed).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
kill: () => close,
|
||||
});
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const scope = yield* Scope.Scope;
|
||||
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(secondClosed).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
kill: () => close,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
yield* manager.stop();
|
||||
yield* instance.stop();
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not restart after stop cancels a scheduled restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
let startCount = 0;
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.sync(() => {
|
||||
startCount += 1;
|
||||
return makeProcess({
|
||||
exitCode: Queue.offer(starts, startCount).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(1)),
|
||||
),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.sync(() => {
|
||||
startCount += 1;
|
||||
return makeProcess({
|
||||
exitCode: Queue.offer(starts, startCount).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(1)),
|
||||
),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* manager.snapshot).restartScheduled;
|
||||
restartScheduled = (yield* instance.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* manager.stop();
|
||||
yield* instance.stop();
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
assert.equal((yield* manager.snapshot).desiredRunning, false);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
assert.equal((yield* instance.snapshot).desiredRunning, false);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,12 +1,35 @@
|
||||
// Per-instance backend factory. Replaces the legacy singleton
|
||||
// `DesktopBackendManager` Context.Service: each call to
|
||||
// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
|
||||
// its own state Ref, mutex, restart loop, and active child process. The
|
||||
// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
|
||||
// methods that operate on that single backend.
|
||||
//
|
||||
// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
|
||||
// backend it wants to run. Today that's the Windows primary; follow-up
|
||||
// commits add a second call for the WSL instance.
|
||||
//
|
||||
// Singleton couplings that the legacy service held inline are now
|
||||
// parameterized via the spec:
|
||||
// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
|
||||
// so each instance can resolve its own start config — the primary wires
|
||||
// `configuration.resolvePrimary`, the WSL orchestrator wires a
|
||||
// `configuration.resolveWsl({ port, distro })` closure.
|
||||
// - onReady / onShutdown drive UI side effects (window auto-open,
|
||||
// readiness latch) only for instances that want them — the primary's
|
||||
// spec passes the window's handleBackendReady/handleBackendNotReady,
|
||||
// other pool instances pass nothing.
|
||||
// - log writes go through a per-instance writer that the factory
|
||||
// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
|
||||
// so each instance lands in its own rotating file.
|
||||
|
||||
import * as Brand from "effect/Brand";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -22,15 +45,19 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
// After this many consecutive fatal preflight failures, stop the silent
|
||||
// restart loop and surface the reason via onPreflightFailed. Transient
|
||||
// failures may instead provide their own larger retryLimit when they should
|
||||
// self-heal for a while but must not leave the app connecting forever.
|
||||
const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
|
||||
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
@@ -43,14 +70,37 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
|
||||
readonly extendEnv: boolean;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
readonly preflightFailure: Option.Option<PreflightFailure>;
|
||||
// Present for a WSL run after the configured/default distro has been
|
||||
// resolved to the concrete distro passed to wsl.exe.
|
||||
readonly runningDistro?: string;
|
||||
}
|
||||
|
||||
// A preflight failure records whether it is fatal. Transient failures (WSL
|
||||
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
|
||||
// self-heal; fatal ones (no node, wrong version, missing build tools) are
|
||||
// surfaced via onPreflightFailed and stop the restart loop after
|
||||
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
|
||||
export interface PreflightFailure {
|
||||
readonly reason: string;
|
||||
readonly fatal: boolean;
|
||||
readonly retryLimit?: number;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
@@ -59,29 +109,38 @@ interface BackendProcessExit {
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
|
||||
readonly url: URL;
|
||||
}> {
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
)<{
|
||||
readonly cause: Schema.SchemaError;
|
||||
}> {
|
||||
{
|
||||
entryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
|
||||
readonly cause: PlatformError.PlatformError;
|
||||
}> {
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
executablePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to spawn desktop backend process: ${this.cause.message}`;
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,20 +165,60 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopBackendManagerShape {
|
||||
// Opaque identifier for one backend process inside the pool. Today only
|
||||
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
|
||||
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
|
||||
// these map 1:1 with environment ids on the frontend; keeping them
|
||||
// desktop-local for now avoids leaking the contracts dependency.
|
||||
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
|
||||
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
|
||||
|
||||
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
);
|
||||
|
||||
// One pooled backend instance. Same lifecycle surface as the legacy
|
||||
// `DesktopBackendManagerShape`; the id and label give the pool registry
|
||||
// + UI something to route on.
|
||||
export interface DesktopBackendInstance {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
// Polls desiredRunning + the instance's own ready flag until the
|
||||
// backend reports ready, or the timeout elapses. Returns true on
|
||||
// ready, false on timeout. Used by the WSL backend swap to drive its
|
||||
// rollback path.
|
||||
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
DesktopBackendManagerShape
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
// Spec describing one backend instance to spawn. The configResolve
|
||||
// effect is awaited each time the instance is (re)started so live
|
||||
// settings changes are picked up on the next start cycle. onReady and
|
||||
// onShutdown let the primary instance trigger UI side effects (window
|
||||
// open, global readiness flag) without coupling the factory to those
|
||||
// concerns; other instances pass them as undefined.
|
||||
export interface BackendInstanceSpec {
|
||||
readonly id: BackendInstanceId;
|
||||
readonly label: Effect.Effect<string>;
|
||||
// configResolve can now fail with PlatformError because the
|
||||
// bootstrap-token closure inside DesktopBackendConfiguration uses
|
||||
// crypto.randomBytes (Effect 4 beta.73 migration).
|
||||
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
|
||||
// Receives the *resolved* httpBaseUrl of the run that just became
|
||||
// ready. The window service uses this to decide what URL to load
|
||||
// (the WSL backend reports its distro IP, the Windows backend reports
|
||||
// 127.0.0.1). Splitting this off from configResolve avoids races
|
||||
// between "fired onReady" and "currentConfig already advanced".
|
||||
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
|
||||
readonly onShutdown?: () => Effect.Effect<void>;
|
||||
// Fired once when a fatal or bounded preflight failure has exhausted its
|
||||
// retries. Returns true when the callback changed configuration and the
|
||||
// manager should resolve once more; false stops the failed instance.
|
||||
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
interface ActiveBackendRun {
|
||||
readonly id: number;
|
||||
@@ -134,6 +233,9 @@ interface BackendManagerState {
|
||||
readonly config: Option.Option<DesktopBackendStartConfig>;
|
||||
readonly active: Option.Option<ActiveBackendRun>;
|
||||
readonly restartAttempt: number;
|
||||
// Consecutive bounded/fatal preflight failures, reset on a clean or
|
||||
// unbounded-transient preflight. restartAttempt counts all restarts.
|
||||
readonly preflightFailureAttempt: number;
|
||||
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
|
||||
readonly nextRunId: number;
|
||||
}
|
||||
@@ -144,6 +246,7 @@ const initialState: BackendManagerState = {
|
||||
config: Option.none(),
|
||||
active: Option.none(),
|
||||
restartAttempt: 0,
|
||||
preflightFailureAttempt: 0,
|
||||
restartFiber: Option.none(),
|
||||
nextRunId: 1,
|
||||
};
|
||||
@@ -176,23 +279,20 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
|
||||
);
|
||||
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(timeout),
|
||||
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
|
||||
);
|
||||
});
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
});
|
||||
};
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
@@ -230,35 +330,38 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: true,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: options.extendEnv,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
@@ -277,18 +380,34 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
// its own state Ref, mutex, restart loop, and active child process;
|
||||
// nothing is shared between instances created from separate
|
||||
// makeBackendInstance calls. The instance shuts down automatically when
|
||||
// the calling scope closes (typically the application scope).
|
||||
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
spec: BackendInstanceSpec,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendInstance,
|
||||
never,
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| Scope.Scope
|
||||
> {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const { logWarning: logInstanceWarning, logError: logInstanceError } =
|
||||
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
|
||||
|
||||
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
|
||||
Ref.update(state, withActiveRun(runId, f));
|
||||
|
||||
@@ -328,10 +447,15 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
if (current.ready) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.ready ? { ...latest, ready: false } : latest,
|
||||
);
|
||||
}
|
||||
const config = yield* spec.configResolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
logInstanceError("failed to generate desktop backend configuration", {
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
@@ -344,14 +468,84 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
.exists(config.value.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const resetFatalPreflightCounter =
|
||||
!current.desiredRunning && current.preflightFailureAttempt > 0;
|
||||
yield* cancelRestart;
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config.value),
|
||||
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
|
||||
}));
|
||||
|
||||
const preflightFailure = config.value.preflightFailure;
|
||||
if (Option.isSome(preflightFailure)) {
|
||||
const { reason, fatal, retryLimit } = preflightFailure.value;
|
||||
if (!fatal && retryLimit === undefined) {
|
||||
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
|
||||
// retrying so the backend self-heals once WSL is ready. Reset a
|
||||
// prior bounded/fatal streak because this is a different failure.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0
|
||||
? latest
|
||||
: { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
|
||||
const attempt = yield* Ref.modify(state, (latest) => {
|
||||
const next = latest.preflightFailureAttempt + 1;
|
||||
return [next, { ...latest, preflightFailureAttempt: next }] as const;
|
||||
});
|
||||
if (attempt > attemptLimit) {
|
||||
// We already surfaced and asked for the Windows fallback, yet we're
|
||||
// still resolving the WSL primary — the fallback didn't take (e.g.
|
||||
// the settings write failed). Stop rather than loop forever.
|
||||
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
|
||||
reason,
|
||||
attempt,
|
||||
});
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (attempt === attemptLimit) {
|
||||
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
|
||||
// on the primary, shows a dialog and persists Windows mode), then
|
||||
// schedule one more restart so the next resolve picks up the Windows
|
||||
// primary and a window can open.
|
||||
yield* logInstanceError(
|
||||
"backend preflight failed repeatedly; surfacing and falling back",
|
||||
{ reason, attempt },
|
||||
);
|
||||
const shouldRestart = yield* (
|
||||
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
|
||||
);
|
||||
if (shouldRestart) {
|
||||
yield* scheduleRestart(reason);
|
||||
} else {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* scheduleRestart(reason);
|
||||
return;
|
||||
}
|
||||
// Clean preflight — reset the fatal counter so a later failure gets a
|
||||
// fresh allowance.
|
||||
yield* Ref.update(state, (latest) =>
|
||||
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
|
||||
);
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
return;
|
||||
@@ -372,7 +566,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
},
|
||||
]);
|
||||
|
||||
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
|
||||
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
@@ -424,7 +618,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -436,7 +630,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
@@ -446,7 +640,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
if (activeRun?.id !== runId) {
|
||||
@@ -466,17 +660,10 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, true);
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
@@ -498,9 +685,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}));
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.withSpan("desktop.backendManager.start"));
|
||||
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
|
||||
|
||||
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
|
||||
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
|
||||
reason: string,
|
||||
) {
|
||||
const scheduled = yield* Ref.modify(state, (latest) => {
|
||||
@@ -520,8 +707,8 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
|
||||
yield* Option.match(scheduled, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
|
||||
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
|
||||
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
});
|
||||
@@ -541,7 +728,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerError("desktop backend restart fiber failed", {
|
||||
logInstanceError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
@@ -560,7 +747,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
});
|
||||
|
||||
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
@@ -578,7 +765,15 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
// Ignore failures from spec.onShutdown so a downstream throw
|
||||
// can't abort the rest of stop(). Ref.modify above already
|
||||
// flipped state to "no active run / no restart fiber", and the
|
||||
// physical cleanup (Fiber.interrupt + closeRun) runs after the
|
||||
// mutex releases. If onShutdown were allowed to propagate, both
|
||||
// would be skipped and the child process + restart fiber would
|
||||
// be orphaned while state claimed nothing was running — the
|
||||
// next start() would then spawn a second backend on top.
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
@@ -593,14 +788,32 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
});
|
||||
|
||||
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
// Return false early if an external `stop()` flipped desiredRunning off
|
||||
// — no point polling for a backend that is being torn down.
|
||||
if (!current.desiredRunning) return { done: true, ready: false };
|
||||
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
|
||||
}).pipe(
|
||||
Effect.repeat({
|
||||
until: (status) => status.done,
|
||||
schedule: Schedule.spaced(Duration.millis(100)),
|
||||
}),
|
||||
Effect.map((status) => status.ready),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse(() => false)),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => stop());
|
||||
|
||||
return DesktopBackendManager.of({
|
||||
return {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
start,
|
||||
stop,
|
||||
currentConfig,
|
||||
snapshot,
|
||||
});
|
||||
waitForReady,
|
||||
} satisfies DesktopBackendInstance;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
|
||||
@@ -0,0 +1,138 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
|
||||
|
||||
function makeStubInstance(
|
||||
id: DesktopBackendPool.BackendInstanceId,
|
||||
label: string,
|
||||
): DesktopBackendPool.DesktopBackendInstance {
|
||||
const snapshot: DesktopBackendSnapshot = {
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
label: Effect.succeed(label),
|
||||
start: Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
|
||||
snapshot: Effect.succeed(snapshot),
|
||||
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
|
||||
};
|
||||
}
|
||||
|
||||
function makePoolLayer(
|
||||
labelRef: Ref.Ref<string>,
|
||||
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
|
||||
return DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
FileSystem.layerNoop({}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
|
||||
),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected HTTP request")),
|
||||
),
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
|
||||
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
|
||||
DesktopAppSettings.layerTest(),
|
||||
ElectronDialog.layer,
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
createMain: Effect.die("unexpected window create"),
|
||||
ensureMain: Effect.die("unexpected window ensure"),
|
||||
revealOrCreateMain: Effect.die("unexpected window reveal"),
|
||||
activate: Effect.die("unexpected window activate"),
|
||||
createMainIfBackendReady: Effect.die("unexpected window create"),
|
||||
showConnectingSplash: Effect.void,
|
||||
handleBackendReady: () => Effect.void,
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("DesktopBackendPool", () => {
|
||||
it.effect("layerTest exposes registered instances by id", () =>
|
||||
Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
|
||||
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
|
||||
const all = yield* pool.list;
|
||||
const resolvedPrimary = yield* pool.primary;
|
||||
|
||||
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
|
||||
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
|
||||
assert.isTrue(Option.isNone(fetchedMissing));
|
||||
assert.lengthOf(all, 2);
|
||||
// First instance becomes primary in layerTest so single-instance
|
||||
// stubs don't have to wire an explicit primary.
|
||||
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendPool.layerTest([
|
||||
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
|
||||
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("layerTest dies when no instances are supplied", () =>
|
||||
Effect.exit(
|
||||
Effect.gen(function* () {
|
||||
yield* DesktopBackendPool.DesktopBackendPool;
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
|
||||
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
|
||||
);
|
||||
|
||||
it.effect("resolves the primary label lazily after pool layer construction", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const labelRef = yield* Ref.make("Windows");
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
|
||||
Effect.provide(makePoolLayer(labelRef)),
|
||||
);
|
||||
const primary = yield* pool.primary;
|
||||
|
||||
yield* Ref.set(labelRef, "WSL (Ubuntu)");
|
||||
|
||||
assert.equal(yield* primary.label, "WSL (Ubuntu)");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,470 @@
|
||||
// Pool registry for multiple backend processes. This file is the entry
|
||||
// point for the concurrent-Windows+WSL-backend feature; see the design
|
||||
// notes below before extending it.
|
||||
//
|
||||
// Current state:
|
||||
// - `DesktopBackendManager.ts` exposes a per-instance factory
|
||||
// (`makeBackendInstance(spec)`); the pool calls it once for the
|
||||
// Windows primary at startup, and `DesktopWslBackend.reconcile`
|
||||
// calls it through `pool.register` to bring up the WSL instance
|
||||
// when the user enables it.
|
||||
// - The primary spec wires `configResolve` to
|
||||
// `DesktopBackendConfiguration.resolvePrimary` and the
|
||||
// `onReady`/`onShutdown` callbacks to the window service. WSL
|
||||
// instances wire `configResolve: configuration.resolveWsl(...)`
|
||||
// and skip onReady/onShutdown — the window only follows the primary.
|
||||
// - The pool exposes `register(spec)` and `unregister(id)`. Each
|
||||
// registered instance gets its own child scope, so unregister can
|
||||
// stop it cleanly without tearing down the pool. The primary's id
|
||||
// refuses unregister.
|
||||
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
|
||||
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
|
||||
// load. IPC surface is `setWslBackendEnabled(boolean)` +
|
||||
// `setWslDistro(string | null)`; both persist and then call the
|
||||
// orchestrator's reconcile. No swap, no rollback, primary stays up.
|
||||
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
|
||||
// pool instance currently registered with bootstrap info. The
|
||||
// primary keeps the "primary" id; WSL instances are "wsl:default"
|
||||
// or "wsl:<distro>".
|
||||
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
|
||||
// it gives the Windows picker — what every existing caller gets,
|
||||
// and what non-WSL users see. WSL targets route to the wsl helpers.
|
||||
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
|
||||
// picker that shows up when the toggle is on. Default-off, so
|
||||
// users who never opted in see the same surface as before.
|
||||
//
|
||||
// Renderer-side wiring (apps/web/src/environments/local/):
|
||||
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
|
||||
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
|
||||
// skips the primary (which the existing primary/ runtime owns),
|
||||
// and for every other entry POSTs the shared bootstrap token to
|
||||
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
|
||||
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
|
||||
// writes the bearer to the secret store, and opens a connection
|
||||
// through the same saved-env path remote envs use.
|
||||
// - The desktopLocal marker filters records out of saved-env
|
||||
// persistence, so toggling WSL off or switching distros doesn't
|
||||
// pollute the user's settings file. The sidebar, CommandPalette,
|
||||
// env switcher, and project-id routing all read the saved-env
|
||||
// registry, so the WSL backend shows up there without any
|
||||
// per-surface changes.
|
||||
//
|
||||
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
|
||||
// wslDistro="Ubuntu"):
|
||||
// - Two backends listening on distinct loopback ports
|
||||
// (server.log: 13773 primary, 13774 wsl).
|
||||
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
|
||||
// - Distinct environment ids reported by each backend's
|
||||
// /.well-known/t3/environment (Windows vs Linux platform).
|
||||
// - Renderer completes the bearer-token bootstrap against the WSL
|
||||
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
|
||||
// ws-token (POST /api/auth/ws-token 200), and holds an
|
||||
// ESTABLISHED WebSocket connection to both ports (netstat).
|
||||
//
|
||||
// Migration history (commits):
|
||||
// 1. Reshape `DesktopBackendManager` into an instance factory and route
|
||||
// consumers through the pool. Pool held a single instance. (a8fc7845)
|
||||
// 2. Drop `DesktopState.backendReady`. The window owns its own
|
||||
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
|
||||
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
|
||||
// 4. Add register/unregister to the pool. (a0eaf560)
|
||||
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
|
||||
// split, DesktopWslBackend orchestrator, new IPC, web compat.
|
||||
// (b1622191 + 31ce3add + 627c80cb)
|
||||
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
|
||||
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
|
||||
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
|
||||
// 9. Register WSL backend as desktop-local saved env via
|
||||
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
|
||||
// 10. CommandPalette enables file-manager picker for desktop-local
|
||||
// envs, routes pickFolder by env id. (38e8477a)
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
const { logWarning: logBackendPoolWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-pool");
|
||||
|
||||
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
|
||||
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
|
||||
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
|
||||
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
|
||||
|
||||
// Caller tried to register an id that's already in the pool. The pool
|
||||
// refuses overwrites so two independent orchestrators racing on the
|
||||
// same id surface as a typed failure instead of one silently winning.
|
||||
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
|
||||
"DesktopBackendPoolInstanceAlreadyRegisteredError",
|
||||
{
|
||||
id: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Backend instance "${this.id}" is already registered in the pool.`;
|
||||
}
|
||||
}
|
||||
|
||||
// Primary instance is registered for the pool's lifetime. Unregister is
|
||||
// a no-op for it today (no real callers), but if someone wires it up
|
||||
// later it's a clear bug rather than something to "handle".
|
||||
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
|
||||
"DesktopBackendPoolCannotUnregisterPrimaryError",
|
||||
{},
|
||||
) {
|
||||
override get message() {
|
||||
return "Refusing to unregister the primary backend from the pool.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendPool extends Context.Service<
|
||||
DesktopBackendPool,
|
||||
{
|
||||
// Look up a registered instance. None when no backend with that id is
|
||||
// currently registered (e.g. WSL backend disabled).
|
||||
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
|
||||
// Snapshot of all currently-registered instances. Order is unspecified;
|
||||
// callers that need a canonical "primary first" view should sort by id.
|
||||
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
|
||||
// Convenience accessor for the always-registered primary instance.
|
||||
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
|
||||
// exposed as a typed effect so consumers don't have to handle the
|
||||
// Option for the case that's guaranteed to be present.
|
||||
readonly primary: Effect.Effect<DesktopBackendInstance>;
|
||||
// Build a fresh DesktopBackendInstance from `spec` and add it to the
|
||||
// registry. The pool owns the instance's scope: unregister(id) or pool
|
||||
// teardown closes it and runs the instance's auto-stop finalizer. The
|
||||
// returned instance has not been started — callers decide when to
|
||||
// start it (and can call start more than once if a retry-after-failure
|
||||
// story makes sense for them).
|
||||
readonly register: (
|
||||
spec: BackendInstanceSpec,
|
||||
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
|
||||
// Stop the named instance and remove it from the registry. Closing the
|
||||
// instance's scope triggers its auto-stop finalizer; the registry is
|
||||
// updated atomically with the scope close so subsequent get(id) calls
|
||||
// observe the unregister before the underlying child process has fully
|
||||
// exited.
|
||||
readonly unregister: (
|
||||
id: BackendInstanceId,
|
||||
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
|
||||
|
||||
// Services required by makeBackendInstance — exported so caller
|
||||
// orchestrators that build their own specs can confirm the layer graph
|
||||
// satisfies them at compile time.
|
||||
export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
readonly instance: DesktopBackendInstance;
|
||||
// None for the primary (which lives in the pool's own layer scope and
|
||||
// is never unregistered); Some for instances added via register, whose
|
||||
// scope unregister closes to stop them.
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
interface ClosingRegisteredInstance {
|
||||
readonly _tag: "Closing";
|
||||
readonly done: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
|
||||
|
||||
type RegisterAction =
|
||||
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
|
||||
|
||||
type UnregisterAction =
|
||||
| { readonly _tag: "Absent" }
|
||||
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
|
||||
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
// Anchor the pool's lifetime to its layer scope so registered
|
||||
// instance scopes can be forked off it. Without this, instance
|
||||
// scopes are orphaned: they only close via explicit unregister()
|
||||
// calls, so on app shutdown the WSL backend child process gets
|
||||
// hard-killed by the OS instead of receiving the graceful
|
||||
// SIGTERM + grace period the instance's stop finalizer would
|
||||
// otherwise run.
|
||||
const layerScope = yield* Scope.Scope;
|
||||
// Capture the services needed to build any future instance from the
|
||||
// pool's layer scope. register() runs `makeBackendInstance` against
|
||||
// a fresh child scope but reuses these services so the instance gets
|
||||
// the same FileSystem, spawner, HTTP client and log factory the
|
||||
// primary instance uses.
|
||||
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
|
||||
|
||||
// A WSL preflight failure on the primary only happens in wsl-only mode.
|
||||
// Fatal configuration failures persist the Windows fallback. Bounded
|
||||
// transport failures use an in-memory fallback for this launch so the app
|
||||
// opens without overwriting the user's WSL preference.
|
||||
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
|
||||
function* (failure: DesktopBackendManager.PreflightFailure) {
|
||||
const { reason, fatal } = failure;
|
||||
if (!fatal) {
|
||||
yield* logBackendPoolWarning(
|
||||
"primary WSL preflight retry window exhausted; using Windows for this launch",
|
||||
{ reason },
|
||||
);
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend is still unavailable",
|
||||
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
|
||||
);
|
||||
yield* appSettings.applyWslWindowsFallbackInMemory;
|
||||
return true;
|
||||
}
|
||||
|
||||
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
|
||||
reason,
|
||||
});
|
||||
yield* electronDialog.showErrorBox(
|
||||
"WSL backend couldn't start",
|
||||
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
|
||||
);
|
||||
// Fully disable the WSL backend — both flags, matching the "Switch to
|
||||
// Windows" recovery path — so the manager's next restart re-resolves the
|
||||
// primary as Windows and reconcile won't register a secondary WSL backend
|
||||
// against the same broken setup. Clearing wslBackendEnabled alone would
|
||||
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
|
||||
// mode the next time they enable WSL. If the persisted write fails, keep
|
||||
// this process recoverable by applying the fallback to in-memory settings.
|
||||
yield* appSettings.applyWslWindowsFallback.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning(
|
||||
"failed to persist Windows fallback after WSL preflight failure",
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const primary = yield* DesktopBackendManager.makeBackendInstance({
|
||||
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
// Keep this lazy. The pool layer is initialized before startup loads
|
||||
// persisted desktop settings, so resolving the primary label here would
|
||||
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
|
||||
// primaries as Windows.
|
||||
label: configuration.resolvePrimaryLabel,
|
||||
configResolve: configuration.resolvePrimary,
|
||||
// Window creation errors propagating out of handleBackendReady must
|
||||
// not block the readiness callback (that would prevent restartAttempt
|
||||
// from being reset), so we absorb them here. The window service only
|
||||
// logs on success, so log the failure here before swallowing it —
|
||||
// otherwise a post-readiness window-open failure vanishes silently and
|
||||
// is near-impossible to diagnose in production.
|
||||
onReady: (httpBaseUrl) =>
|
||||
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendPoolWarning("failed to open main window after backend readiness", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
onShutdown: () => desktopWindow.handleBackendNotReady,
|
||||
onPreflightFailed: handlePrimaryPreflightFailure,
|
||||
});
|
||||
|
||||
const instancesRef = yield* SynchronizedRef.make<
|
||||
ReadonlyMap<BackendInstanceId, RegisteredInstance>
|
||||
>(
|
||||
new Map([
|
||||
[
|
||||
DesktopBackendManager.PRIMARY_INSTANCE_ID,
|
||||
{ _tag: "Active", instance: primary, scope: Option.none() },
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
|
||||
Effect.suspend(() =>
|
||||
SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
|
||||
DesktopBackendPoolInstanceAlreadyRegisteredError
|
||||
> => {
|
||||
const existing = current.get(spec.id);
|
||||
if (existing?._tag === "Active") {
|
||||
return Effect.fail(
|
||||
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
|
||||
);
|
||||
}
|
||||
if (existing?._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: existing.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
// Provide the captured factory services first, then the child scope
|
||||
// last so instance finalizers are owned by the unregisterable scope.
|
||||
const instanceScope = yield* Scope.fork(layerScope, "sequential");
|
||||
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
|
||||
Effect.provide(factoryContext),
|
||||
Scope.provide(instanceScope),
|
||||
);
|
||||
const next = new Map(current);
|
||||
next.set(spec.id, {
|
||||
_tag: "Active",
|
||||
instance,
|
||||
scope: Option.some(instanceScope),
|
||||
});
|
||||
return [
|
||||
{ _tag: "Registered", instance } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const;
|
||||
});
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result._tag === "Registered"
|
||||
? Effect.succeed(result.instance)
|
||||
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
|
||||
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
|
||||
}
|
||||
const done = yield* Deferred.make<void>();
|
||||
const action = yield* SynchronizedRef.modifyEffect(
|
||||
instancesRef,
|
||||
(
|
||||
current,
|
||||
): Effect.Effect<
|
||||
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
|
||||
> => {
|
||||
const entry = current.get(id);
|
||||
if (entry === undefined) {
|
||||
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
|
||||
}
|
||||
if (entry._tag === "Closing") {
|
||||
return Effect.succeed([
|
||||
{ _tag: "Wait", done: entry.done } as const,
|
||||
current,
|
||||
] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(id, { _tag: "Closing", done });
|
||||
return Effect.succeed([
|
||||
{ _tag: "Close", entry } as const,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
},
|
||||
);
|
||||
|
||||
if (action._tag === "Absent") return;
|
||||
if (action._tag === "Wait") {
|
||||
yield* Deferred.await(action.done);
|
||||
return;
|
||||
}
|
||||
|
||||
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
|
||||
const closing = current.get(id);
|
||||
if (closing?._tag !== "Closing" || closing.done !== done) {
|
||||
return Effect.succeed([undefined, current] as const);
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(id);
|
||||
return Effect.succeed([
|
||||
undefined,
|
||||
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
|
||||
] as const);
|
||||
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
|
||||
yield* Option.match(action.entry.scope, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
|
||||
}).pipe(Effect.ensuring(finish));
|
||||
});
|
||||
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) =>
|
||||
SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) => {
|
||||
const entry = instances.get(id);
|
||||
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
|
||||
}),
|
||||
),
|
||||
list: SynchronizedRef.get(instancesRef).pipe(
|
||||
Effect.map((instances) =>
|
||||
Array.from(instances.values()).flatMap((entry) =>
|
||||
entry._tag === "Active" ? [entry.instance] : [],
|
||||
),
|
||||
),
|
||||
),
|
||||
primary: Effect.succeed(primary),
|
||||
register,
|
||||
unregister,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Test layer for unit tests that want to assert against a known pool
|
||||
// composition without standing up the full manager. Each provided
|
||||
// instance is registered under its own id; the first one is also
|
||||
// surfaced as `primary` so callers can stub a single-instance pool.
|
||||
// `register` and `unregister` are stubbed to die so tests that
|
||||
// accidentally exercise pool registration fail loudly instead of
|
||||
// silently noop'ing.
|
||||
export const layerTest = (
|
||||
instances: readonly DesktopBackendInstance[],
|
||||
): Layer.Layer<DesktopBackendPool> =>
|
||||
Layer.effect(
|
||||
DesktopBackendPool,
|
||||
Effect.gen(function* () {
|
||||
if (instances.length === 0) {
|
||||
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
|
||||
}
|
||||
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
|
||||
instances.map((instance) => [instance.id, instance] as const),
|
||||
);
|
||||
const primary = instances[0]!;
|
||||
return DesktopBackendPool.of({
|
||||
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
|
||||
list: Effect.succeed(Array.from(byId.values())),
|
||||
primary: Effect.succeed(primary),
|
||||
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
|
||||
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,81 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
const config = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: {},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: 3773,
|
||||
t3Home: "/tmp/t3",
|
||||
host: "127.0.0.1",
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
};
|
||||
|
||||
describe("DesktopLocalEnvironmentAuth", () => {
|
||||
it.effect("exchanges the desktop bootstrap credential only once", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestCount = yield* Ref.make(0);
|
||||
const httpClientLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Ref.update(requestCount, (count) => count + 1).pipe(
|
||||
Effect.as(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
access_token: "desktop-bearer-token",
|
||||
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
scope: "orchestration:read",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
|
||||
list: Effect.succeed([
|
||||
{
|
||||
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
currentConfig: Effect.succeed(Option.some(config)),
|
||||
},
|
||||
]),
|
||||
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
|
||||
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
|
||||
);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
|
||||
return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
assert.strictEqual(first, "desktop-bearer-token");
|
||||
assert.strictEqual(second, "desktop-bearer-token");
|
||||
assert.strictEqual(yield* Ref.get(requestCount), 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
|
||||
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Local backend is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
|
||||
"DesktopLocalEnvironmentAuthSessionBootstrapError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create the local desktop bearer session.";
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopLocalEnvironmentAuthError = Schema.Union([
|
||||
DesktopLocalEnvironmentAuthBackendNotConfiguredError,
|
||||
DesktopLocalEnvironmentAuthSessionBootstrapError,
|
||||
]);
|
||||
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
{
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const pool = yield* DesktopBackendPool.DesktopBackendPool;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const instances = yield* pool.list;
|
||||
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
|
||||
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const credential = config.bootstrap.desktopBootstrapToken;
|
||||
if (!credential) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthSessionBootstrapError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
|
||||
@@ -0,0 +1,65 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { networkInterfacesMock } = vi.hoisted(() => ({
|
||||
networkInterfacesMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:os", () => ({
|
||||
networkInterfaces: networkInterfacesMock,
|
||||
}));
|
||||
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
describe("DesktopNetworkInterfaces", () => {
|
||||
beforeEach(() => {
|
||||
networkInterfacesMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("reads network interfaces through the service", () => {
|
||||
const interfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.10",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
networkInterfacesMock.mockReturnValueOnce(interfaces);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
assert.strictEqual(yield* service.read, interfaces);
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
|
||||
it.effect("preserves network interface read failures as structured defects", () => {
|
||||
const cause = new Error("network interface probe failed");
|
||||
networkInterfacesMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const exit = yield* Effect.exit(service.read);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type NetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
|
||||
"DesktopNetworkInterfacesReadError",
|
||||
{
|
||||
platform: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read desktop network interfaces on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfaces extends Context.Service<
|
||||
DesktopNetworkInterfaces,
|
||||
{
|
||||
readonly read: Effect.Effect<NetworkInterfaces>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return DesktopNetworkInterfaces.of({
|
||||
read: Effect.try({
|
||||
try: () => NodeOS.networkInterfaces(),
|
||||
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
|
||||
@@ -7,21 +7,18 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopEnvironment,
|
||||
layer as makeDesktopEnvironmentLayer,
|
||||
} from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.20",
|
||||
@@ -31,7 +28,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
],
|
||||
};
|
||||
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.90.1.2",
|
||||
@@ -64,8 +61,15 @@ function mockSpawnerLayer(statusJson = "{}") {
|
||||
);
|
||||
}
|
||||
|
||||
function dieOnSpawnLayer() {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
|
||||
);
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return makeDesktopEnvironmentLayer({
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
@@ -84,20 +88,22 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
|
||||
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
|
||||
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
|
||||
});
|
||||
|
||||
return DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(mockSpawnerLayer()),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
Layer.provideMerge(networkLayer),
|
||||
Layer.provideMerge(DesktopConfig.layerTest(env)),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
@@ -105,24 +111,36 @@ function makeLayer(input: {
|
||||
}
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
| R
|
||||
| DesktopEnvironment
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| FileSystem.FileSystem
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-server-exposure-test-",
|
||||
});
|
||||
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
|
||||
return yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
baseDir,
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopServerExposure", () => {
|
||||
@@ -222,6 +240,73 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves persistence request context and the settings failure chain", () => {
|
||||
const diskFailure = new Error("disk exploded");
|
||||
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: "/tmp/desktop-settings.json",
|
||||
cause: diskFailure,
|
||||
});
|
||||
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.fail(settingsFailure),
|
||||
setTailscaleServe: () => Effect.fail(settingsFailure),
|
||||
setUpdateChannel: () => Effect.die("unexpected update channel change"),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
|
||||
|
||||
return withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
|
||||
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
modeError,
|
||||
DesktopServerExposure.DesktopServerExposureModePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
|
||||
assert.equal(modeError.mode, "network-accessible");
|
||||
assert.strictEqual(modeError.cause, settingsFailure);
|
||||
assert.strictEqual(modeError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
modeError.message,
|
||||
"Failed to persist desktop server exposure mode network-accessible.",
|
||||
);
|
||||
assert.notInclude(modeError.message, diskFailure.message);
|
||||
|
||||
const tailscaleError = yield* serverExposure
|
||||
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
tailscaleError,
|
||||
DesktopServerExposure.DesktopTailscaleServePersistenceError,
|
||||
);
|
||||
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
|
||||
assert.equal(tailscaleError.enabled, true);
|
||||
assert.equal(tailscaleError.port, 8443);
|
||||
assert.strictEqual(tailscaleError.cause, settingsFailure);
|
||||
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
|
||||
assert.equal(
|
||||
tailscaleError.message,
|
||||
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
|
||||
);
|
||||
assert.notInclude(tailscaleError.message, diskFailure.message);
|
||||
}),
|
||||
{},
|
||||
undefined,
|
||||
settingsLayer,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
|
||||
withHarness(
|
||||
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
|
||||
@@ -239,6 +324,27 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
// mode stays at default "local-only", tailscaleServeEnabled stays false.
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
|
||||
// would have crashed the test if the gate was missing.
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["http://127.0.0.1:4173/"],
|
||||
);
|
||||
}),
|
||||
{},
|
||||
dieOnSpawnLayer(),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses ConfigProvider desktop exposure overrides", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
|
||||
@@ -1,46 +1,35 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/shared/advertisedEndpoint";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
import {
|
||||
DesktopServerExposureModeSchema,
|
||||
type AdvertisedEndpoint,
|
||||
type AdvertisedEndpointProvider,
|
||||
type DesktopServerExposureMode,
|
||||
type DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
|
||||
|
||||
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type DesktopNetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
interface ResolvedDesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
@@ -87,7 +76,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
|
||||
};
|
||||
|
||||
const resolveLanAdvertisedHost = (
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
explicitHost: string | undefined,
|
||||
): string | null => {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
@@ -112,7 +101,7 @@ const resolveLanAdvertisedHost = (
|
||||
const resolveDesktopServerExposure = (input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): ResolvedDesktopServerExposure => {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
@@ -214,34 +203,56 @@ const resolveDesktopCoreAdvertisedEndpoints = (
|
||||
return endpoints;
|
||||
};
|
||||
|
||||
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
|
||||
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
|
||||
"DesktopServerExposureNoNetworkAddressError",
|
||||
)<{
|
||||
readonly port: number;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No reachable network address is available for desktop network access on port ${this.port}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
)<{
|
||||
readonly operation: DesktopServerExposurePersistenceOperation;
|
||||
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
|
||||
"DesktopServerExposureModePersistenceError",
|
||||
{
|
||||
mode: DesktopServerExposureModeSchema,
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop server exposure mode ${this.mode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopServerExposureSetModeError =
|
||||
| DesktopServerExposureNoNetworkAddressError
|
||||
| DesktopServerExposurePersistenceError;
|
||||
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
|
||||
"DesktopTailscaleServePersistenceError",
|
||||
{
|
||||
enabled: Schema.Boolean,
|
||||
port: Schema.NullOr(Schema.Number),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
|
||||
export const DesktopServerExposureSetModeError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
|
||||
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
|
||||
|
||||
export const DesktopServerExposureError = Schema.Union([
|
||||
DesktopServerExposureNoNetworkAddressError,
|
||||
DesktopServerExposureModePersistenceError,
|
||||
DesktopTailscaleServePersistenceError,
|
||||
]);
|
||||
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
|
||||
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
|
||||
|
||||
export interface DesktopServerExposureBackendConfig {
|
||||
readonly port: number;
|
||||
@@ -256,36 +267,25 @@ export interface DesktopServerExposureChange {
|
||||
readonly requiresRelaunch: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopServerExposureShape {
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
|
||||
export class DesktopServerExposure extends Context.Service<
|
||||
DesktopServerExposure,
|
||||
DesktopServerExposureShape
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
|
||||
export interface DesktopNetworkInterfacesServiceShape {
|
||||
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfacesService extends Context.Service<
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesServiceShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
|
||||
|
||||
interface RuntimeState {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
@@ -307,10 +307,10 @@ interface ResolvedRuntimeState {
|
||||
|
||||
const initialRuntimeState = (): RuntimeState =>
|
||||
runtimeStateFromResolvedExposure({
|
||||
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DEFAULT_DESKTOP_SETTINGS,
|
||||
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
exposure: resolveDesktopServerExposure({
|
||||
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
port: 0,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
@@ -344,7 +344,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
|
||||
|
||||
function runtimeStateFromResolvedExposure(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly exposure: ResolvedDesktopServerExposure;
|
||||
readonly port: number;
|
||||
}): RuntimeState {
|
||||
@@ -365,9 +365,9 @@ function runtimeStateFromResolvedExposure(input: {
|
||||
|
||||
function resolveRuntimeState(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride: Option.Option<string>;
|
||||
}): ResolvedRuntimeState {
|
||||
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
|
||||
@@ -404,14 +404,26 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
|
||||
previous.bindHost !== next.bindHost ||
|
||||
previous.localHttpUrl !== next.localHttpUrl;
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfacesService;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
|
||||
// spawn re-triggers the "Other apps" TCC prompt.
|
||||
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
),
|
||||
TAILSCALE_STATUS_CACHE_TTL,
|
||||
);
|
||||
|
||||
const readNetworkInterfaces = networkInterfaces.read;
|
||||
|
||||
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
|
||||
@@ -460,8 +472,8 @@ const make = Effect.gen(function* () {
|
||||
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "server-exposure-mode",
|
||||
new DesktopServerExposureModePersistenceError({
|
||||
mode,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -488,8 +500,9 @@ const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopServerExposurePersistenceError({
|
||||
operation: "tailscale-serve",
|
||||
new DesktopTailscaleServePersistenceError({
|
||||
enabled: input.enabled,
|
||||
port: input.port ?? null,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -516,11 +529,20 @@ const make = Effect.gen(function* () {
|
||||
exposure: toResolvedExposure(state),
|
||||
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
|
||||
});
|
||||
|
||||
// Don't spawn the Tailscale CLI when the user hasn't opted into any
|
||||
// network exposure. The spawn itself triggers a macOS "Other apps"
|
||||
// TCC prompt on Mac App Store Tailscale builds.
|
||||
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
|
||||
return coreEndpoints;
|
||||
}
|
||||
|
||||
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: state.port,
|
||||
serveEnabled: state.tailscaleServeEnabled,
|
||||
servePort: state.tailscaleServePort,
|
||||
networkInterfaces: currentNetworkInterfaces,
|
||||
readMagicDnsName: cachedReadMagicDnsName,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
@@ -539,10 +561,3 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopServerExposure, make);
|
||||
|
||||
export const networkInterfacesLayer = Layer.succeed(
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesService.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
}),
|
||||
);
|
||||
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
|
||||
Effect.gen(function* () {
|
||||
let readerCalls = 0;
|
||||
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
readMagicDnsName: Effect.sync(() => {
|
||||
readerCalls += 1;
|
||||
return "desktop.tail.ts.net";
|
||||
}),
|
||||
});
|
||||
assert.equal(readerCalls, 1);
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["https://desktop.tail.ts.net/"],
|
||||
);
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
|
||||
() =>
|
||||
|
||||
@@ -9,10 +9,10 @@ import {
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
|
||||
function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
@@ -103,8 +103,13 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
>;
|
||||
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
|
||||
}): Effect.fn.Return<
|
||||
readonly AdvertisedEndpoint[],
|
||||
@@ -112,12 +117,15 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
|
||||
> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const readDnsName =
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? yield* readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
? yield* readDnsName
|
||||
: input.statusJson
|
||||
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.orElseSucceed(() => null),
|
||||
|
||||
@@ -100,6 +100,44 @@ describe("ElectronApp", () => {
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports which app metadata property failed", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("version unavailable");
|
||||
getVersionMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.metadata.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
|
||||
assert.strictEqual(error.property, "app-version");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
'Failed to read Electron app metadata property "app-version".',
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves Electron readiness failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("ready failed");
|
||||
whenReadyMock.mockRejectedValueOnce(cause);
|
||||
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const error = yield* electronApp.whenReady.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
|
||||
assert.strictEqual(error.isPackaged, true);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Failed to wait for the Electron app to become ready (packaged: true).",
|
||||
);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes app event listeners", () =>
|
||||
Effect.gen(function* () {
|
||||
const listener = vi.fn();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
@@ -13,41 +14,64 @@ export interface ElectronAppMetadata {
|
||||
readonly runningUnderArm64Translation: boolean;
|
||||
}
|
||||
|
||||
export interface ElectronAppShape {
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void>;
|
||||
readonly quit: Effect.Effect<void>;
|
||||
readonly exit: (code: number) => Effect.Effect<void>;
|
||||
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
|
||||
readonly setPath: (
|
||||
name: Parameters<Electron.App["setPath"]>[0],
|
||||
path: string,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setName: (name: string) => Effect.Effect<void>;
|
||||
readonly setAboutPanelOptions: (
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
|
||||
"ElectronAppMetadataReadError",
|
||||
{
|
||||
property: Schema.Literals(["app-version", "app-path"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read Electron app metadata property "${this.property}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
|
||||
"@t3tools/desktop/electron/ElectronApp",
|
||||
) {}
|
||||
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
|
||||
"ElectronAppWhenReadyError",
|
||||
{
|
||||
isPackaged: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<
|
||||
ElectronApp,
|
||||
{
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
|
||||
readonly quit: Effect.Effect<void>;
|
||||
readonly exit: (code: number) => Effect.Effect<void>;
|
||||
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
|
||||
readonly setPath: (
|
||||
name: Parameters<Electron.App["setPath"]>[0],
|
||||
path: string,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setName: (name: string) => Effect.Effect<void>;
|
||||
readonly setAboutPanelOptions: (
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
path?: string,
|
||||
args?: readonly string[],
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly setDesktopName: (desktopName: string) => Effect.Effect<void>;
|
||||
readonly setDockIcon: (iconPath: string) => Effect.Effect<void>;
|
||||
readonly appendCommandLineSwitch: (switchName: string, value?: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronApp") {}
|
||||
|
||||
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
@@ -63,16 +87,41 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const make = ElectronApp.of({
|
||||
metadata: Effect.sync(() => ({
|
||||
appVersion: Electron.app.getVersion(),
|
||||
appPath: Electron.app.getAppPath(),
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
})),
|
||||
export const make = ElectronApp.of({
|
||||
metadata: Effect.gen(function* () {
|
||||
const appVersion = yield* Effect.try({
|
||||
try: () => Electron.app.getVersion(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-version",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const appPath = yield* Effect.try({
|
||||
try: () => Electron.app.getAppPath(),
|
||||
catch: (cause) =>
|
||||
new ElectronAppMetadataReadError({
|
||||
property: "app-path",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
appVersion,
|
||||
appPath,
|
||||
isPackaged: Electron.app.isPackaged,
|
||||
resourcesPath: process.resourcesPath,
|
||||
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
|
||||
};
|
||||
}),
|
||||
name: Effect.sync(() => Electron.app.name),
|
||||
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
|
||||
whenReady: Effect.gen(function* () {
|
||||
const isPackaged = Electron.app.isPackaged;
|
||||
yield* Effect.tryPromise({
|
||||
try: () => Electron.app.whenReady(),
|
||||
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
|
||||
});
|
||||
}),
|
||||
quit: Effect.sync(() => {
|
||||
Electron.app.quit();
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import type { BrowserWindow } from "electron";
|
||||
@@ -90,4 +91,116 @@ describe("ElectronDialog", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
const owner = { id: 7 } as BrowserWindow;
|
||||
showOpenDialogMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.pickFolder({
|
||||
owner: Option.some(owner),
|
||||
defaultPath: Option.some("/workspace"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
|
||||
assert.isTrue(ElectronDialog.isElectronDialogError(error));
|
||||
assert.strictEqual(error.ownerWindowId, 7);
|
||||
assert.strictEqual(error.defaultPath, "/workspace");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 7");
|
||||
assert.include(error.message, "/workspace");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.showMessageBox({
|
||||
type: "warning",
|
||||
title: "Unsaved changes",
|
||||
message: "Discard changes?",
|
||||
detail: "This cannot be undone.",
|
||||
buttons: ["Cancel", "Discard"],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
|
||||
assert.strictEqual(error.type, "warning");
|
||||
assert.strictEqual(error.titleLength, "Unsaved changes".length);
|
||||
assert.strictEqual(error.messageLength, "Discard changes?".length);
|
||||
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
|
||||
assert.strictEqual(error.buttonCount, 2);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "dialogMessage");
|
||||
assert.notProperty(error, "dialogDetail");
|
||||
assert.notProperty(error, "buttons");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "warning");
|
||||
assert.notInclude(error.message, "Unsaved changes");
|
||||
assert.notInclude(error.message, "Discard changes?");
|
||||
assert.notInclude(error.message, "This cannot be undone.");
|
||||
assert.notInclude(error.message, "Cancel");
|
||||
assert.notInclude(error.message, "Discard");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves error box request context and cause in the defect", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("error box failed");
|
||||
showErrorBoxMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
|
||||
|
||||
assert.isTrue(exit._tag === "Failure");
|
||||
if (exit._tag === "Success") return;
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
|
||||
assert.strictEqual(error.titleLength, "Startup failed".length);
|
||||
assert.strictEqual(error.contentLength, "Could not start.".length);
|
||||
assert.notProperty(error, "title");
|
||||
assert.notProperty(error, "content");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, "Startup failed");
|
||||
assert.notInclude(error.message, "Could not start.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
});
|
||||
@@ -2,11 +2,80 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
|
||||
titleLength: Schema.NullOr(Schema.Number),
|
||||
messageLength: Schema.Number,
|
||||
detailLength: Schema.NullOr(Schema.Number),
|
||||
buttonCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const type = this.type === null ? "untyped" : this.type;
|
||||
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
|
||||
"ElectronDialogShowErrorBoxError",
|
||||
{
|
||||
titleLength: Schema.Number,
|
||||
contentLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
export type ElectronDialogError = typeof ElectronDialogError.Type;
|
||||
export const isElectronDialogError = Schema.is(ElectronDialogError);
|
||||
|
||||
export interface ElectronDialogPickFolderInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
@@ -17,23 +86,29 @@ export interface ElectronDialogConfirmInput {
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export interface ElectronDialogShape {
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
export class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronDialog") {}
|
||||
|
||||
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
|
||||
"@t3tools/desktop/electron/ElectronDialog",
|
||||
) {}
|
||||
|
||||
const make = ElectronDialog.of({
|
||||
export const make = ElectronDialog.of({
|
||||
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
|
||||
onNone: () => ({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
@@ -43,10 +118,18 @@ const make = ElectronDialog.of({
|
||||
defaultPath,
|
||||
}),
|
||||
});
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
|
||||
onSome: (owner) =>
|
||||
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFolderError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
@@ -68,17 +151,48 @@ const make = ElectronDialog.of({
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const result = yield* Option.match(input.owner, {
|
||||
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
|
||||
showErrorBox: (title, content) =>
|
||||
Effect.sync(() => {
|
||||
Electron.dialog.showErrorBox(title, content);
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowMessageBoxError({
|
||||
type: options.type ?? null,
|
||||
titleLength: options.title?.length ?? null,
|
||||
messageLength: options.message.length,
|
||||
detailLength: options.detail?.length ?? null,
|
||||
buttonCount: options.buttons?.length ?? 0,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
showErrorBox: (title, content) =>
|
||||
Effect.try({
|
||||
try: () => Electron.dialog.showErrorBox(title, content),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogShowErrorBoxError({
|
||||
titleLength: title.length,
|
||||
contentLength: content.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronDialog, make);
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
@@ -22,19 +24,40 @@ export interface ElectronMenuTemplateInput {
|
||||
readonly template: readonly Electron.MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
export interface ElectronMenuShape {
|
||||
readonly setApplicationMenu: (
|
||||
template: readonly Electron.MenuItemConstructorOptions[],
|
||||
) => Effect.Effect<void>;
|
||||
readonly showContextMenu: (
|
||||
input: ElectronMenuContextInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
|
||||
const ElectronMenuOperation = Schema.Literals([
|
||||
"set-application-menu",
|
||||
"popup-template",
|
||||
"show-context-menu",
|
||||
]);
|
||||
|
||||
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
|
||||
"ElectronMenuOperationError",
|
||||
{
|
||||
operation: ElectronMenuOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
itemCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
|
||||
"@t3tools/desktop/electron/ElectronMenu",
|
||||
) {}
|
||||
export class ElectronMenu extends Context.Service<
|
||||
ElectronMenu,
|
||||
{
|
||||
readonly setApplicationMenu: (
|
||||
template: readonly Electron.MenuItemConstructorOptions[],
|
||||
) => Effect.Effect<void>;
|
||||
readonly showContextMenu: (
|
||||
input: ElectronMenuContextInput,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly popupTemplate: (input: ElectronMenuTemplateInput) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronMenu") {}
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
const normalizedItems: ContextMenuItem[] = [];
|
||||
@@ -44,6 +67,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
continue;
|
||||
}
|
||||
|
||||
// Header items are decorative section labels for the web fallback only —
|
||||
// Electron's native menu has no equivalent affordance, so we skip them.
|
||||
if (sourceItem.header === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedItem: ContextMenuItem = {
|
||||
id: sourceItem.id,
|
||||
label: sourceItem.label,
|
||||
@@ -65,19 +94,27 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
// Renderer positions arrive in CSS pixels; popup() expects window points, so
|
||||
// page zoom must be factored in or menus drift proportionally to their
|
||||
// distance from the window origin.
|
||||
const normalizePosition = (
|
||||
position: Option.Option<ElectronMenuPosition>,
|
||||
zoomFactor: number,
|
||||
): Option.Option<ElectronMenuPosition> =>
|
||||
Option.filter(
|
||||
position,
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
({ x, y }) =>
|
||||
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
|
||||
).pipe(
|
||||
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
|
||||
);
|
||||
|
||||
export const layer = Layer.sync(ElectronMenu, () => {
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
let destructiveMenuIconCache: Option.Option<Electron.NativeImage> | undefined;
|
||||
|
||||
const getDestructiveMenuIcon = (): Option.Option<Electron.NativeImage> => {
|
||||
if (process.platform !== "darwin") {
|
||||
if (platform !== "darwin") {
|
||||
return Option.none();
|
||||
}
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
@@ -89,6 +126,7 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
width: 12,
|
||||
height: 12,
|
||||
});
|
||||
icon.setTemplateImage(true);
|
||||
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
|
||||
} catch {
|
||||
destructiveMenuIconCache = Option.none();
|
||||
@@ -134,16 +172,36 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
|
||||
return ElectronMenu.of({
|
||||
setApplicationMenu: (template) =>
|
||||
Effect.sync(() => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
}),
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "set-application-menu",
|
||||
platform,
|
||||
windowId: null,
|
||||
itemCount: template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
popupTemplate: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.template.length === 0) {
|
||||
return;
|
||||
}
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
|
||||
}),
|
||||
input.template.length === 0
|
||||
? Effect.void
|
||||
: Effect.try({
|
||||
try: () =>
|
||||
Electron.Menu.buildFromTemplate([...input.template]).popup({
|
||||
window: input.window,
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronMenuOperationError({
|
||||
operation: "popup-template",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: input.template.length,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
showContextMenu: (input) =>
|
||||
Effect.callback<Option.Option<string>>((resume) => {
|
||||
const normalizedItems = normalizeContextMenuItems(input.items);
|
||||
@@ -161,21 +219,44 @@ export const layer = Layer.sync(ElectronMenu, () => {
|
||||
resume(Effect.succeed(selectedItemId));
|
||||
};
|
||||
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
try {
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(
|
||||
input.position,
|
||||
input.window.webContents.getZoomFactor(),
|
||||
);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
onSome: (position): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
callback: () => complete(Option.none()),
|
||||
}),
|
||||
});
|
||||
menu.popup(popupOptions);
|
||||
} catch (cause) {
|
||||
if (completed) {
|
||||
return;
|
||||
}
|
||||
completed = true;
|
||||
resume(
|
||||
Effect.die(
|
||||
new ElectronMenuOperationError({
|
||||
operation: "show-context-menu",
|
||||
platform,
|
||||
windowId: input.window.id,
|
||||
itemCount: normalizedItems.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronMenu, make);
|
||||
@@ -1,105 +1,229 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
|
||||
vi.hoisted(() => ({
|
||||
registerFileProtocolMock: vi.fn(),
|
||||
registerSchemesAsPrivilegedMock: vi.fn(),
|
||||
unregisterProtocolMock: vi.fn(),
|
||||
}));
|
||||
const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
netFetchMock: vi.fn(),
|
||||
unhandleMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
protocol: {
|
||||
registerFileProtocol: registerFileProtocolMock,
|
||||
registerSchemesAsPrivileged: registerSchemesAsPrivilegedMock,
|
||||
unregisterProtocol: unregisterProtocolMock,
|
||||
},
|
||||
net: { fetch: netFetchMock },
|
||||
protocol: { handle: handleMock, unhandle: unhandleMock },
|
||||
}));
|
||||
|
||||
import * as ElectronProtocol from "./ElectronProtocol.ts";
|
||||
|
||||
describe("ElectronProtocol", () => {
|
||||
beforeEach(() => {
|
||||
registerFileProtocolMock.mockReset();
|
||||
registerSchemesAsPrivilegedMock.mockReset();
|
||||
unregisterProtocolMock.mockReset();
|
||||
handleMock.mockReset();
|
||||
netFetchMock.mockReset();
|
||||
unhandleMock.mockReset();
|
||||
});
|
||||
|
||||
it("normalizes safe desktop protocol pathnames", () => {
|
||||
assert.equal(
|
||||
Option.getOrNull(ElectronProtocol.normalizeDesktopProtocolPathname("/settings/./general")),
|
||||
"settings/general",
|
||||
);
|
||||
assert.isTrue(Option.isNone(ElectronProtocol.normalizeDesktopProtocolPathname("/../secret")));
|
||||
});
|
||||
it.effect("proxies the stable renderer origin to the current app server", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock.mockResolvedValue(new Response("ok"));
|
||||
|
||||
it.effect("registers desktop scheme privileges through a layer", () =>
|
||||
Effect.scoped(
|
||||
Layer.build(ElectronProtocol.layerSchemePrivileges).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
assert.deepEqual(registerSchemesAsPrivilegedMock.mock.calls, [
|
||||
[
|
||||
[
|
||||
{
|
||||
scheme: "t3",
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"img-src 'self' t3code-dev: blob: data: http: https:",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"font-src 'self' t3code-dev: data:",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
handleMock.mock.calls.map((call) => call[0]),
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("scopes registered file protocols", () =>
|
||||
it.effect("rejects custom protocol requests for another host", () =>
|
||||
Effect.gen(function* () {
|
||||
let capturedHandler:
|
||||
| ((
|
||||
request: Electron.ProtocolRequest,
|
||||
callback: (response: Electron.ProtocolResponse) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
|
||||
registerFileProtocolMock.mockImplementation((_scheme, handler) => {
|
||||
capturedHandler = handler;
|
||||
return true;
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* electronProtocol.registerFileProtocol({
|
||||
scheme: "t3",
|
||||
handler: () => Effect.succeed({ path: "/app/index.html" }),
|
||||
});
|
||||
|
||||
assert.isDefined(capturedHandler);
|
||||
return yield* Effect.callback<Electron.ProtocolResponse>((resume) => {
|
||||
capturedHandler?.({ url: "t3://app/" } as Electron.ProtocolRequest, (response) =>
|
||||
resume(Effect.succeed(response)),
|
||||
);
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code://other/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(response, { path: "/app/index.html" });
|
||||
assert.deepEqual(
|
||||
registerFileProtocolMock.mock.calls.map((call) => call[0]),
|
||||
["t3"],
|
||||
);
|
||||
assert.deepEqual(unregisterProtocolMock.mock.calls, [["t3"]]);
|
||||
assert.equal(response.status, 404);
|
||||
assert.equal(netFetchMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
handleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const error = yield* Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3774/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
|
||||
assert.equal(error.scheme, "t3code-dev");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol unregistration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol unregistration failed");
|
||||
unhandleMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
protocol.registerDesktopProtocol({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
|
||||
assert.equal(error.scheme, "t3code");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
|
||||
}
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
|
||||
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
|
||||
scheme: "t3code",
|
||||
targetOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: "clerk.t3.codes",
|
||||
});
|
||||
const directives = Object.fromEntries(
|
||||
policy.split("; ").map((directive) => {
|
||||
const [name, ...sources] = directive.split(" ");
|
||||
return [name, sources];
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
|
||||
assert.deepEqual(directives["img-src"], [
|
||||
"'self'",
|
||||
"t3code:",
|
||||
"blob:",
|
||||
"data:",
|
||||
"http:",
|
||||
"https:",
|
||||
]);
|
||||
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
|
||||
});
|
||||
});
|
||||
@@ -1,272 +1,206 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
|
||||
export const DESKTOP_HOST = "app";
|
||||
export const DESKTOP_PRODUCTION_SCHEME = "t3code";
|
||||
export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
|
||||
|
||||
export const DESKTOP_SCHEME = "t3";
|
||||
export function getDesktopScheme(isDevelopment: boolean): string {
|
||||
return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Data.TaggedError(
|
||||
export function getDesktopOrigin(isDevelopment: boolean): string {
|
||||
return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
|
||||
}
|
||||
|
||||
export function getDesktopUrl(isDevelopment: boolean): string {
|
||||
return `${getDesktopOrigin(isDevelopment)}/`;
|
||||
}
|
||||
|
||||
export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<ElectronProtocolRegistrationError>()(
|
||||
"ElectronProtocolRegistrationError",
|
||||
)<{
|
||||
readonly scheme: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to register ${this.scheme}: file protocol.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
|
||||
"ElectronProtocolStaticBundleMissingError",
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ElectronProtocolShape {
|
||||
readonly registerFileProtocol: <E, R>(input: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
|
||||
readonly registerDesktopFileProtocol: Effect.Effect<
|
||||
void,
|
||||
ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
|
||||
FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
|
||||
>;
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
|
||||
const segments: string[] = [];
|
||||
for (const segment of rawPath.split("/")) {
|
||||
if (segment.length === 0 || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
return Option.none();
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return Option.some(segments.join("/"));
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(() => {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
const resolveDesktopStaticDir: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
never,
|
||||
FileSystem.FileSystem | DesktopEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidates = [
|
||||
environment.path.join(environment.appRoot, "apps/server/dist/client"),
|
||||
environment.path.join(environment.appRoot, "apps/web/dist"),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const hasIndex = yield* fileSystem
|
||||
.exists(environment.path.join(candidate, "index.html"))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (hasIndex) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
|
||||
function* (
|
||||
staticRoot: string,
|
||||
requestUrl: string,
|
||||
): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
|
||||
if (Option.isNone(normalizedPath)) {
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
|
||||
const resolvedPath = environment.path.join(staticRoot, requestedPath);
|
||||
|
||||
if (environment.path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = environment.path.join(resolvedPath, "index.html");
|
||||
const nestedIndexExists = yield* fileSystem
|
||||
.exists(nestedIndex)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (nestedIndexExists) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return environment.path.join(staticRoot, "index.html");
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
);
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return environment.path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
|
||||
"ElectronProtocolUnregistrationError",
|
||||
{
|
||||
scheme: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
|
||||
}
|
||||
}
|
||||
|
||||
const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
|
||||
function* <E, R>({
|
||||
scheme,
|
||||
handler,
|
||||
onFailure,
|
||||
}: {
|
||||
readonly scheme: string;
|
||||
readonly handler: (
|
||||
request: Electron.ProtocolRequest,
|
||||
) => Effect.Effect<Electron.ProtocolResponse, E, R>;
|
||||
readonly onFailure?: (
|
||||
request: Electron.ProtocolRequest,
|
||||
cause: Cause.Cause<E>,
|
||||
) => Electron.ProtocolResponse;
|
||||
}): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
|
||||
yield* Effect.annotateCurrentSpan({ scheme });
|
||||
const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
|
||||
Effect.map((protocols) => protocols.has(scheme)),
|
||||
);
|
||||
if (alreadyRegistered) {
|
||||
return;
|
||||
}
|
||||
export interface DesktopProtocolRegistrationInput {
|
||||
readonly scheme: string;
|
||||
readonly targetOrigin: URL;
|
||||
readonly backendOrigin: URL;
|
||||
readonly clerkFrontendApiHostname: string | undefined;
|
||||
}
|
||||
|
||||
const context = yield* Effect.context<R>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
export class ElectronProtocol extends Context.Service<
|
||||
ElectronProtocol,
|
||||
{
|
||||
readonly registerDesktopProtocol: (
|
||||
input: DesktopProtocolRegistrationInput,
|
||||
) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronProtocol") {}
|
||||
|
||||
export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
|
||||
const clerkOrigin = input.clerkFrontendApiHostname
|
||||
? `https://${input.clerkFrontendApiHostname}`
|
||||
: undefined;
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
// The renderer connects directly to user-configured environments in addition to
|
||||
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
|
||||
// origins are not known when this response policy is created, so restrict
|
||||
// connections by the network schemes the client supports instead of by host.
|
||||
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
|
||||
|
||||
return [
|
||||
"default-src 'self'",
|
||||
`script-src ${scriptSources.join(" ")}`,
|
||||
`connect-src ${connectSources.join(" ")}`,
|
||||
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`font-src 'self' ${input.scheme}: data:`,
|
||||
"worker-src 'self' blob:",
|
||||
"frame-src 'self' https://challenges.cloudflare.com",
|
||||
"form-action 'self'",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
function withContentSecurityPolicy(response: Response, policy: string): Response {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Content-Security-Policy", policy);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
contentSecurityPolicy: string,
|
||||
): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (requestUrl.host !== DESKTOP_HOST) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
|
||||
function* (input: DesktopProtocolRegistrationInput) {
|
||||
if (yield* Ref.get(registered)) return;
|
||||
|
||||
const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const registered = Electron.protocol.registerFileProtocol(
|
||||
scheme,
|
||||
(request, callback) => {
|
||||
const response = handler(request).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
|
||||
),
|
||||
);
|
||||
|
||||
void runPromise(response).then(callback, () => callback({ error: -2 }));
|
||||
},
|
||||
Electron.protocol.handle(input.scheme, (request) =>
|
||||
proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
|
||||
);
|
||||
if (!registered) {
|
||||
throw new ElectronProtocolRegistrationError({
|
||||
scheme,
|
||||
cause: "registerFileProtocol returned false",
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof ElectronProtocolRegistrationError
|
||||
? cause
|
||||
: new ElectronProtocolRegistrationError({ scheme, cause }),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
|
||||
),
|
||||
),
|
||||
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, true))),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.protocol.unregisterProtocol(scheme);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(registeredProtocols, (protocols) => {
|
||||
const next = new Set(protocols);
|
||||
next.delete(scheme);
|
||||
return next;
|
||||
Effect.try({
|
||||
try: () => Electron.protocol.unhandle(input.scheme),
|
||||
catch: (cause) =>
|
||||
new ElectronProtocolUnregistrationError({
|
||||
scheme: input.scheme,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const registerDesktopFileProtocol = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment;
|
||||
if (environment.isDevelopment) return;
|
||||
|
||||
const staticRoot = yield* resolveDesktopStaticDir;
|
||||
if (Option.isNone(staticRoot)) {
|
||||
return yield* new ElectronProtocolStaticBundleMissingError();
|
||||
}
|
||||
|
||||
const staticRootResolved = environment.path.resolve(staticRoot.value);
|
||||
const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
|
||||
const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
|
||||
|
||||
yield* registerFileProtocol({
|
||||
scheme: DESKTOP_SCHEME,
|
||||
handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment;
|
||||
const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = environment.path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url, environment);
|
||||
const exists = yield* fileSystem
|
||||
.exists(resolvedCandidate)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
if (!isInRoot || !exists) {
|
||||
return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
|
||||
}
|
||||
|
||||
return { path: resolvedCandidate } as const;
|
||||
}),
|
||||
onFailure: () => ({ path: fallbackIndex }),
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
|
||||
|
||||
return ElectronProtocol.of({
|
||||
registerFileProtocol,
|
||||
registerDesktopFileProtocol,
|
||||
});
|
||||
return ElectronProtocol.of({ registerDesktopProtocol });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ElectronProtocol, make);
|
||||
@@ -1,56 +1,69 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ElectronSafeStorageAvailabilityError extends Schema.TaggedErrorClass<ElectronSafeStorageAvailabilityError>()(
|
||||
"ElectronSafeStorageAvailabilityError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to check encryption availability.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageEncryptError extends Data.TaggedError(
|
||||
export class ElectronSafeStorageEncryptError extends Schema.TaggedErrorClass<ElectronSafeStorageEncryptError>()(
|
||||
"ElectronSafeStorageEncryptError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to encrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronSafeStorageDecryptError extends Data.TaggedError(
|
||||
export class ElectronSafeStorageDecryptError extends Schema.TaggedErrorClass<ElectronSafeStorageDecryptError>()(
|
||||
"ElectronSafeStorageDecryptError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
...electronSafeStorageErrorFields,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Electron safe storage failed to decrypt a string.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ElectronSafeStorageShape {
|
||||
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
|
||||
readonly encryptString: (
|
||||
value: string,
|
||||
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
}
|
||||
export const ElectronSafeStorageError = Schema.Union([
|
||||
ElectronSafeStorageAvailabilityError,
|
||||
ElectronSafeStorageEncryptError,
|
||||
ElectronSafeStorageDecryptError,
|
||||
]);
|
||||
export type ElectronSafeStorageError = typeof ElectronSafeStorageError.Type;
|
||||
export const isElectronSafeStorageError = Schema.is(ElectronSafeStorageError);
|
||||
|
||||
export class ElectronSafeStorage extends Context.Service<
|
||||
ElectronSafeStorage,
|
||||
ElectronSafeStorageShape
|
||||
{
|
||||
readonly isEncryptionAvailable: Effect.Effect<boolean, ElectronSafeStorageAvailabilityError>;
|
||||
readonly encryptString: (
|
||||
value: string,
|
||||
) => Effect.Effect<Uint8Array, ElectronSafeStorageEncryptError>;
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
const make = ElectronSafeStorage.of({
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
|
||||
@@ -20,16 +20,15 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
export interface ElectronShellShape {
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
|
||||
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
|
||||
"@t3tools/desktop/electron/ElectronShell",
|
||||
) {}
|
||||
|
||||
const make = ElectronShell.of({
|
||||
export const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
|
||||
@@ -8,6 +8,7 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
|
||||
themeState: {
|
||||
shouldUseDarkColors: true,
|
||||
themeSource: "system",
|
||||
setSourceError: null as unknown,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -17,6 +18,9 @@ vi.mock("electron", () => ({
|
||||
return themeState.shouldUseDarkColors;
|
||||
},
|
||||
set themeSource(value: string) {
|
||||
if (themeState.setSourceError !== null) {
|
||||
throw themeState.setSourceError;
|
||||
}
|
||||
themeState.themeSource = value;
|
||||
},
|
||||
on: onMock,
|
||||
@@ -32,6 +36,7 @@ describe("ElectronTheme", () => {
|
||||
removeListenerMock.mockClear();
|
||||
themeState.shouldUseDarkColors = true;
|
||||
themeState.themeSource = "system";
|
||||
themeState.setSourceError = null;
|
||||
});
|
||||
|
||||
it.effect("scopes native theme update listeners", () =>
|
||||
@@ -49,4 +54,21 @@ describe("ElectronTheme", () => {
|
||||
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the requested source and cause when setting the theme fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("theme source failed");
|
||||
themeState.setSourceError = cause;
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
|
||||
const error = yield* Effect.flip(electronTheme.setSource("dark"));
|
||||
|
||||
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
|
||||
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
|
||||
assert.strictEqual(error.source, "dark");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "dark");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronTheme.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,27 +1,43 @@
|
||||
import type { DesktopTheme } from "@t3tools/contracts";
|
||||
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export interface ElectronThemeShape {
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
|
||||
"ElectronThemeSetSourceError",
|
||||
{
|
||||
source: DesktopThemeSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to set the Electron theme source to ${this.source}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
|
||||
"@t3tools/desktop/electron/ElectronTheme",
|
||||
) {}
|
||||
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
|
||||
|
||||
const make = ElectronTheme.of({
|
||||
export class ElectronTheme extends Context.Service<
|
||||
ElectronTheme,
|
||||
{
|
||||
readonly shouldUseDarkColors: Effect.Effect<boolean>;
|
||||
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
|
||||
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronTheme") {}
|
||||
|
||||
export const make = ElectronTheme.of({
|
||||
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
|
||||
setSource: (theme) =>
|
||||
Effect.suspend(() => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
return Effect.void;
|
||||
Effect.try({
|
||||
try: () => {
|
||||
Electron.nativeTheme.themeSource = theme;
|
||||
},
|
||||
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
|
||||
}),
|
||||
onUpdated: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
@@ -11,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
|
||||
autoInstallOnAppQuit: true,
|
||||
channel: "latest",
|
||||
disableDifferentialDownload: false,
|
||||
fullChangelog: false,
|
||||
checkForUpdates: vi.fn(() => Promise.resolve(null)),
|
||||
downloadUpdate: vi.fn(() => Promise.resolve([])),
|
||||
on: vi.fn(),
|
||||
@@ -34,6 +34,7 @@ describe("ElectronUpdater", () => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true;
|
||||
autoUpdaterMock.channel = "latest";
|
||||
autoUpdaterMock.disableDifferentialDownload = false;
|
||||
autoUpdaterMock.fullChangelog = false;
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
|
||||
autoUpdaterMock.downloadUpdate.mockClear();
|
||||
@@ -65,15 +66,77 @@ describe("ElectronUpdater", () => {
|
||||
const cause = new Error("network unavailable");
|
||||
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "beta";
|
||||
|
||||
const exit = yield* Effect.exit(updater.checkForUpdates);
|
||||
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.equal(error.cause, cause);
|
||||
}
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "beta");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves the execution-time channel on download failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("download unavailable");
|
||||
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "nightly";
|
||||
|
||||
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to download the update on channel nightly.",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("sets full changelog mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
|
||||
yield* updater.setFullChangelog(true);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, true);
|
||||
|
||||
yield* updater.setFullChangelog(false);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, false);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
autoUpdaterMock.channel = "alpha";
|
||||
|
||||
const error = yield* updater
|
||||
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
|
||||
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
|
||||
assert.equal(error.channel, "alpha");
|
||||
assert.equal(error.isSilent, true);
|
||||
assert.equal(error.isForceRunAfter, false);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { autoUpdater } from "electron-updater";
|
||||
@@ -10,67 +10,78 @@ type AutoUpdater = typeof autoUpdater;
|
||||
|
||||
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
|
||||
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Data.TaggedError(
|
||||
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
|
||||
"ElectronUpdaterCheckForUpdatesError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to check for updates.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterDownloadUpdateError extends Data.TaggedError(
|
||||
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
|
||||
"ElectronUpdaterDownloadUpdateError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to download the update.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronUpdaterQuitAndInstallError extends Data.TaggedError(
|
||||
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
|
||||
"ElectronUpdaterQuitAndInstallError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Electron updater failed to quit and install the update.";
|
||||
{
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
isSilent: Schema.Boolean,
|
||||
isForceRunAfter: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ElectronUpdaterError =
|
||||
| ElectronUpdaterCheckForUpdatesError
|
||||
| ElectronUpdaterDownloadUpdateError
|
||||
| ElectronUpdaterQuitAndInstallError;
|
||||
export const ElectronUpdaterError = Schema.Union([
|
||||
ElectronUpdaterCheckForUpdatesError,
|
||||
ElectronUpdaterDownloadUpdateError,
|
||||
ElectronUpdaterQuitAndInstallError,
|
||||
]);
|
||||
export type ElectronUpdaterError = typeof ElectronUpdaterError.Type;
|
||||
export const isElectronUpdaterError = Schema.is(ElectronUpdaterError);
|
||||
|
||||
export interface ElectronUpdaterShape {
|
||||
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
|
||||
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setChannel: (channel: string) => Effect.Effect<void>;
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
readonly quitAndInstall: (options: {
|
||||
readonly isSilent: boolean;
|
||||
readonly isForceRunAfter: boolean;
|
||||
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
export class ElectronUpdater extends Context.Service<
|
||||
ElectronUpdater,
|
||||
{
|
||||
readonly setFeedURL: (options: ElectronUpdaterFeedUrl) => Effect.Effect<void>;
|
||||
readonly setAutoDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setAutoInstallOnAppQuit: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setChannel: (channel: string) => Effect.Effect<void>;
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
readonly quitAndInstall: (options: {
|
||||
readonly isSilent: boolean;
|
||||
readonly isForceRunAfter: boolean;
|
||||
}) => Effect.Effect<void, ElectronUpdaterQuitAndInstallError>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronUpdater") {}
|
||||
|
||||
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
|
||||
"@t3tools/desktop/electron/ElectronUpdater",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, {
|
||||
export const make = ElectronUpdater.of({
|
||||
setFeedURL: (options) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.setFeedURL(options);
|
||||
@@ -102,23 +113,43 @@ export const layer = Layer.succeed(ElectronUpdater, {
|
||||
autoUpdater.allowDowngrade = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.fullChangelog = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setDisableDifferentialDownload: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
checkForUpdates: Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
downloadUpdate: Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
|
||||
}).pipe(Effect.asVoid),
|
||||
checkForUpdates: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.checkForUpdates(),
|
||||
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
downloadUpdate: Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.tryPromise({
|
||||
try: () => autoUpdater.downloadUpdate(),
|
||||
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
|
||||
}).pipe(Effect.asVoid);
|
||||
}),
|
||||
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
|
||||
Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
|
||||
Effect.suspend(() => {
|
||||
const channel = autoUpdater.channel;
|
||||
return Effect.try({
|
||||
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
|
||||
catch: (cause) =>
|
||||
new ElectronUpdaterQuitAndInstallError({
|
||||
channel,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
on: (eventName, listener) => {
|
||||
const eventTarget = autoUpdater as unknown as {
|
||||
@@ -136,4 +167,6 @@ export const layer = Layer.succeed(ElectronUpdater, {
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
},
|
||||
} satisfies ElectronUpdaterShape);
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, make);
|
||||
@@ -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)),
|
||||
);
|
||||
});
|
||||
@@ -1,47 +1,135 @@
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export class ElectronWindowCreateError extends Data.TaggedError("ElectronWindowCreateError")<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
const ElectronWindowCreateOptions = Schema.Struct({
|
||||
title: Schema.NullOr(Schema.String),
|
||||
width: Schema.NullOr(Schema.Number),
|
||||
height: Schema.NullOr(Schema.Number),
|
||||
minWidth: Schema.NullOr(Schema.Number),
|
||||
minHeight: Schema.NullOr(Schema.Number),
|
||||
show: Schema.NullOr(Schema.Boolean),
|
||||
modal: Schema.NullOr(Schema.Boolean),
|
||||
frame: Schema.NullOr(Schema.Boolean),
|
||||
transparent: Schema.NullOr(Schema.Boolean),
|
||||
backgroundColor: Schema.NullOr(Schema.String),
|
||||
webPreferences: Schema.Struct({
|
||||
preload: Schema.NullOr(Schema.String),
|
||||
partition: Schema.NullOr(Schema.String),
|
||||
sandbox: Schema.NullOr(Schema.Boolean),
|
||||
contextIsolation: Schema.NullOr(Schema.Boolean),
|
||||
nodeIntegration: Schema.NullOr(Schema.Boolean),
|
||||
webviewTag: Schema.NullOr(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
|
||||
const ElectronWindowOperation = Schema.Literals([
|
||||
"list-windows",
|
||||
"get-focused-window",
|
||||
"inspect-window",
|
||||
"reveal-window",
|
||||
"send-window-message",
|
||||
"destroy-window",
|
||||
]);
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
options: ElectronWindowCreateOptions,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
|
||||
const dimensions =
|
||||
this.options.width === null || this.options.height === null
|
||||
? ""
|
||||
: ` (${this.options.width}x${this.options.height})`;
|
||||
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ElectronWindowShape {
|
||||
readonly create: (
|
||||
options: Electron.BrowserWindowConstructorOptions,
|
||||
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
|
||||
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
|
||||
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
|
||||
readonly destroyAll: Effect.Effect<void>;
|
||||
readonly syncAllAppearance: <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) => Effect.Effect<void, E, R>;
|
||||
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
operation: ElectronWindowOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
|
||||
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
|
||||
"@t3tools/desktop/electron/ElectronWindow",
|
||||
) {}
|
||||
export class ElectronWindow extends Context.Service<
|
||||
ElectronWindow,
|
||||
{
|
||||
readonly create: (
|
||||
options: Electron.BrowserWindowConstructorOptions,
|
||||
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
|
||||
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
|
||||
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
|
||||
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
|
||||
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
|
||||
readonly destroyAll: Effect.Effect<void>;
|
||||
readonly syncAllAppearance: <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) => Effect.Effect<void, E, R>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronWindow") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
Effect.map(Option.filter((value) => !value.isDestroyed())),
|
||||
);
|
||||
const listWindows = Effect.try({
|
||||
try: () => Electron.BrowserWindow.getAllWindows(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "list-windows",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
|
||||
Effect.try({
|
||||
try: () => window.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "inspect-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const liveMain = Effect.gen(function* () {
|
||||
const main = yield* Ref.get(mainWindowRef);
|
||||
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return main;
|
||||
});
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const main = yield* liveMain;
|
||||
@@ -49,27 +137,60 @@ const make = Effect.gen(function* () {
|
||||
return main;
|
||||
}
|
||||
|
||||
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
);
|
||||
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
|
||||
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return first;
|
||||
});
|
||||
|
||||
const focusedMainOrFirst = Effect.sync(() =>
|
||||
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
),
|
||||
).pipe(
|
||||
Effect.flatMap((focused) =>
|
||||
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
|
||||
),
|
||||
);
|
||||
const focusedMainOrFirst = Effect.gen(function* () {
|
||||
const focused = yield* Effect.try({
|
||||
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "get-focused-window",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
|
||||
return focused;
|
||||
}
|
||||
return yield* currentMainOrFirst;
|
||||
});
|
||||
|
||||
return ElectronWindow.of({
|
||||
create: (options) =>
|
||||
Effect.try({
|
||||
create: (options) => {
|
||||
const webPreferences = options.webPreferences;
|
||||
const diagnosticOptions = {
|
||||
title: options.title ?? null,
|
||||
width: options.width ?? null,
|
||||
height: options.height ?? null,
|
||||
minWidth: options.minWidth ?? null,
|
||||
minHeight: options.minHeight ?? null,
|
||||
show: options.show ?? null,
|
||||
modal: options.modal ?? null,
|
||||
frame: options.frame ?? null,
|
||||
transparent: options.transparent ?? null,
|
||||
backgroundColor: options.backgroundColor ?? null,
|
||||
webPreferences: {
|
||||
preload: webPreferences?.preload ?? null,
|
||||
partition: webPreferences?.partition ?? null,
|
||||
sandbox: webPreferences?.sandbox ?? null,
|
||||
contextIsolation: webPreferences?.contextIsolation ?? null,
|
||||
nodeIntegration: webPreferences?.nodeIntegration ?? null,
|
||||
webviewTag: webPreferences?.webviewTag ?? null,
|
||||
},
|
||||
} satisfies typeof ElectronWindowCreateOptions.Type;
|
||||
|
||||
return Effect.try({
|
||||
try: () => new Electron.BrowserWindow(options),
|
||||
catch: (cause) => new ElectronWindowCreateError({ cause }),
|
||||
}),
|
||||
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
|
||||
});
|
||||
},
|
||||
main: liveMain,
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst,
|
||||
@@ -85,45 +206,75 @@ const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
}),
|
||||
reveal: (window) =>
|
||||
Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "reveal-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
window.webContents.send(channel, ...args);
|
||||
yield* Effect.try({
|
||||
try: () => window.webContents.send(channel, ...args),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
destroyAll: Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
window.destroy();
|
||||
destroyAll: Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
yield* Effect.try({
|
||||
try: () => window.destroy(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "destroy-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) {
|
||||
const windows = Electron.BrowserWindow.getAllWindows();
|
||||
const windows = yield* listWindows;
|
||||
for (const window of windows) {
|
||||
if (window.isDestroyed()) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
continue;
|
||||
}
|
||||
yield* sync(window);
|
||||
|
||||
@@ -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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
@@ -23,6 +24,39 @@ export interface DesktopIpcMain {
|
||||
on(channel: string, listener: DesktopIpcSyncListener): void;
|
||||
}
|
||||
|
||||
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
|
||||
"DesktopIpcRegistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
|
||||
"DesktopIpcUnregistrationError",
|
||||
{
|
||||
handlerKind: Schema.Literals(["invoke", "sync"]),
|
||||
channel: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopIpcError = Schema.Union([
|
||||
DesktopIpcRegistrationError,
|
||||
DesktopIpcUnregistrationError,
|
||||
]);
|
||||
export type DesktopIpcError = typeof DesktopIpcError.Type;
|
||||
export const isDesktopIpcError = Schema.is(DesktopIpcError);
|
||||
|
||||
export interface DesktopIpcMethod<E, R> {
|
||||
readonly channel: string;
|
||||
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
|
||||
@@ -33,20 +67,19 @@ export interface DesktopSyncIpcMethod<E, R> {
|
||||
readonly handler: () => Effect.Effect<unknown, E, R>;
|
||||
}
|
||||
|
||||
export interface DesktopIpcShape {
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
export class DesktopIpc extends Context.Service<
|
||||
DesktopIpc,
|
||||
{
|
||||
readonly handle: <E, R>(
|
||||
input: DesktopIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
readonly handleSync: <E, R>(
|
||||
input: DesktopSyncIpcMethod<E, R>,
|
||||
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/ipc/DesktopIpc") {}
|
||||
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
|
||||
DesktopIpc.of({
|
||||
handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
|
||||
channel,
|
||||
@@ -57,18 +90,27 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeHandler(channel);
|
||||
ipcMain.handle(channel, (_event, raw) =>
|
||||
runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler(raw);
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
|
||||
),
|
||||
);
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
}),
|
||||
() => Effect.sync(() => ipcMain.removeHandler(channel)),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeHandler(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -81,22 +123,36 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
const runSync = Effect.runSyncWith(context);
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
|
||||
);
|
||||
});
|
||||
Effect.try({
|
||||
try: () => {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
ipcMain.on(channel, (event) => {
|
||||
event.returnValue = runSync(
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel });
|
||||
return yield* handler();
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ channel }),
|
||||
Effect.withSpan("desktop.ipc.invokeSync"),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
|
||||
}),
|
||||
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
|
||||
() =>
|
||||
Effect.try({
|
||||
try: () => ipcMain.removeAllListeners(channel),
|
||||
catch: (cause) =>
|
||||
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
|
||||
|
||||
/**
|
||||
* Convenience helpers for creating IPC methods
|
||||
*/
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as DesktopIpc from "./DesktopIpc.ts";
|
||||
import {
|
||||
clearCloudAuthToken,
|
||||
createCloudAuthRequest,
|
||||
fetchCloudAuth,
|
||||
getCloudAuthToken,
|
||||
setCloudAuthToken,
|
||||
} from "./methods/cloudAuth.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import {
|
||||
getSavedEnvironmentRegistry,
|
||||
getSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
setSavedEnvironmentRegistry,
|
||||
setSavedEnvironmentSecret,
|
||||
} from "./methods/savedEnvironments.ts";
|
||||
clearConnectionCatalog,
|
||||
getConnectionCatalog,
|
||||
setConnectionCatalog,
|
||||
} from "./methods/connectionCatalog.ts";
|
||||
import {
|
||||
getAdvertisedEndpoints,
|
||||
getServerExposureState,
|
||||
@@ -42,26 +33,31 @@ import {
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstrap,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
yield* ipc.handle(getClientSettings);
|
||||
yield* ipc.handle(setClientSettings);
|
||||
yield* ipc.handle(getSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(setSavedEnvironmentRegistry);
|
||||
yield* ipc.handle(getSavedEnvironmentSecret);
|
||||
yield* ipc.handle(setSavedEnvironmentSecret);
|
||||
yield* ipc.handle(removeSavedEnvironmentSecret);
|
||||
yield* ipc.handle(getConnectionCatalog);
|
||||
yield* ipc.handle(setConnectionCatalog);
|
||||
yield* ipc.handle(clearConnectionCatalog);
|
||||
|
||||
yield* ipc.handle(discoverSshHosts);
|
||||
yield* ipc.handle(ensureSshEnvironment);
|
||||
@@ -77,19 +73,22 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(setTailscaleServeEnabled);
|
||||
yield* ipc.handle(getAdvertisedEndpoints);
|
||||
|
||||
yield* ipc.handle(getWslState);
|
||||
yield* ipc.handle(setWslBackendEnabled);
|
||||
yield* ipc.handle(setWslDistro);
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
yield* ipc.handle(createCloudAuthRequest);
|
||||
yield* ipc.handle(getCloudAuthToken);
|
||||
yield* ipc.handle(setCloudAuthToken);
|
||||
yield* ipc.handle(clearCloudAuthToken);
|
||||
yield* ipc.handle(fetchCloudAuth);
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
yield* ipc.handle(installUpdate);
|
||||
yield* ipc.handle(checkForUpdate);
|
||||
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
|
||||
for (const previewMethod of PreviewIpc.methods) {
|
||||
yield* ipc.handle(previewMethod);
|
||||
}
|
||||
});
|
||||
@@ -3,13 +3,9 @@ export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const CREATE_CLOUD_AUTH_REQUEST_CHANNEL = "desktop:create-cloud-auth-request";
|
||||
export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
|
||||
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
|
||||
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
|
||||
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
|
||||
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
@@ -17,14 +13,14 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
|
||||
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
|
||||
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
|
||||
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
@@ -38,4 +34,43 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state";
|
||||
export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
|
||||
export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
|
||||
export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
|
||||
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
|
||||
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
|
||||
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
|
||||
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
|
||||
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
|
||||
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
|
||||
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
|
||||
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
|
||||
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
|
||||
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
|
||||
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
|
||||
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
|
||||
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
|
||||
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
|
||||
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
|
||||
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
|
||||
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
|
||||
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
|
||||
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
|
||||
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
|
||||
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
|
||||
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
|
||||
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
|
||||
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
|
||||
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
|
||||
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
|
||||
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
|
||||
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
|
||||
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
|
||||
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
|
||||
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
|
||||
@@ -5,9 +5,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getClientSettings = makeIpcMethod({
|
||||
export const getClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(ClientSettingsSchema),
|
||||
@@ -17,7 +17,7 @@ export const getClientSettings = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const setClientSettings = makeIpcMethod({
|
||||
export const setClientSettings = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLIENT_SETTINGS_CHANNEL,
|
||||
payload: ClientSettingsSchema,
|
||||
result: Schema.Void,
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
function makeHttpClientLayer(
|
||||
handler: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
|
||||
) {
|
||||
return Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => handler(request)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "sign_in_attempt" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-mobile": "1",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(
|
||||
forwardedRequest.headers["content-type"],
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(forwardedRequest.body._tag, "Uint8Array");
|
||||
if (forwardedRequest.body._tag === "Uint8Array") {
|
||||
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "client" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://clerk.t3.codes/v1/client",
|
||||
method: "GET",
|
||||
headers: {},
|
||||
});
|
||||
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
assert.throws(
|
||||
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
|
||||
/restricted to Clerk Frontend API HTTPS hosts/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,154 +0,0 @@
|
||||
import {
|
||||
DesktopCloudAuthFetchInputSchema,
|
||||
DesktopCloudAuthFetchResultSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
clerkFrontendApiHostnameFromPublishableKey,
|
||||
isAllowedClerkFrontendApiHostname,
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
|
||||
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
|
||||
readonly reason: string;
|
||||
readonly cause?: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return this.reason;
|
||||
}
|
||||
}
|
||||
|
||||
function configuredClerkFrontendApiHostname(): string | null {
|
||||
const publishableKey =
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
|
||||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
|
||||
? ""
|
||||
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
|
||||
if (!publishableKey) return null;
|
||||
|
||||
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
|
||||
}
|
||||
|
||||
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
|
||||
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
|
||||
|
||||
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
|
||||
throw new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
|
||||
});
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export const createCloudAuthRequest = makeIpcMethod({
|
||||
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
|
||||
const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
|
||||
return yield* cloudAuth.createRequest;
|
||||
}),
|
||||
});
|
||||
|
||||
export const getCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return Option.getOrNull(yield* tokenStore.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
return yield* tokenStore.set(token);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCloudAuthToken = makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
|
||||
const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
|
||||
yield* tokenStore.clear;
|
||||
}),
|
||||
});
|
||||
|
||||
export const fetchCloudAuth = makeIpcMethod({
|
||||
channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
|
||||
payload: DesktopCloudAuthFetchInputSchema,
|
||||
result: DesktopCloudAuthFetchResultSchema,
|
||||
handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
|
||||
const url = yield* Effect.try({
|
||||
try: () => validateClerkFrontendApiUrl(input.url),
|
||||
catch: (cause) =>
|
||||
cause instanceof DesktopCloudAuthFetchError
|
||||
? cause
|
||||
: new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch received an invalid URL.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
|
||||
url,
|
||||
{
|
||||
headers: input.headers,
|
||||
},
|
||||
);
|
||||
const request =
|
||||
input.body === undefined
|
||||
? requestWithoutBody
|
||||
: HttpClientRequest.bodyText(
|
||||
requestWithoutBody,
|
||||
input.body,
|
||||
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
|
||||
);
|
||||
|
||||
const response = yield* HttpClient.execute(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const getConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return Option.getOrNull(yield* store.get);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
return yield* store.set(catalog);
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearConnectionCatalog = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* store.clear;
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import * as PreviewIpc from "./preview.ts";
|
||||
|
||||
const { fromPartition } = vi.hoisted(() => ({
|
||||
fromPartition: vi.fn(() => {
|
||||
throw new Error("Session can only be received when app is ready");
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
BrowserWindow: {
|
||||
getAllWindows: vi.fn(() => []),
|
||||
},
|
||||
session: {
|
||||
fromPartition,
|
||||
},
|
||||
webContents: {
|
||||
fromId: vi.fn(() => null),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("preview IPC methods", () => {
|
||||
beforeEach(() => {
|
||||
fromPartition.mockClear();
|
||||
});
|
||||
|
||||
it("does not access the Electron session while the module loads", async () => {
|
||||
await expect(import("./preview.ts")).resolves.toBeDefined();
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
|
||||
Effect.map(
|
||||
PreviewIpc.registerWebview
|
||||
.handler({ tabId: "tab-1", webContentsId: 0 })
|
||||
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
|
||||
(exit) => {
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isSuccess(exit)) return;
|
||||
const error = Cause.findErrorOption(exit.cause);
|
||||
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
|
||||
expect(fromPartition).not.toHaveBeenCalled();
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
import {
|
||||
DesktopPreviewAnnotationThemeInputSchema,
|
||||
DesktopPreviewArtifactInputSchema,
|
||||
DesktopPreviewAutomationClickInputSchema,
|
||||
DesktopPreviewAutomationEvaluateInputSchema,
|
||||
DesktopPreviewAutomationPressInputSchema,
|
||||
DesktopPreviewAutomationScrollInputSchema,
|
||||
DesktopPreviewAutomationTypeInputSchema,
|
||||
DesktopPreviewAutomationWaitForInputSchema,
|
||||
DesktopPreviewConfigInputSchema,
|
||||
DesktopPreviewNavigateInputSchema,
|
||||
DesktopPreviewRecordingArtifactSchema,
|
||||
DesktopPreviewRecordingSaveInputSchema,
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
|
||||
);
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
|
||||
);
|
||||
});
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.createTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const closeTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.closeTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const registerWebview = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
|
||||
payload: DesktopPreviewRegisterWebviewInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.registerWebview(tabId, webContentsId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const navigate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
|
||||
payload: DesktopPreviewNavigateInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.navigate(tabId, url);
|
||||
}),
|
||||
});
|
||||
|
||||
const tabMethod = (
|
||||
channel: string,
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
DesktopIpc.makeIpcMethod({
|
||||
channel,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn(name)(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* invoke(manager, tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const goBack = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
|
||||
"desktop.ipc.preview.goBack",
|
||||
(manager, tabId) => manager.goBack(tabId),
|
||||
);
|
||||
export const goForward = tabMethod(
|
||||
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
|
||||
"desktop.ipc.preview.goForward",
|
||||
(manager, tabId) => manager.goForward(tabId),
|
||||
);
|
||||
export const refresh = tabMethod(
|
||||
IpcChannels.PREVIEW_REFRESH_CHANNEL,
|
||||
"desktop.ipc.preview.refresh",
|
||||
(manager, tabId) => manager.refresh(tabId),
|
||||
);
|
||||
export const zoomIn = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
|
||||
"desktop.ipc.preview.zoomIn",
|
||||
(manager, tabId) => manager.zoomIn(tabId),
|
||||
);
|
||||
export const zoomOut = tabMethod(
|
||||
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
|
||||
"desktop.ipc.preview.zoomOut",
|
||||
(manager, tabId) => manager.zoomOut(tabId),
|
||||
);
|
||||
export const resetZoom = tabMethod(
|
||||
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
|
||||
"desktop.ipc.preview.resetZoom",
|
||||
(manager, tabId) => manager.resetZoom(tabId),
|
||||
);
|
||||
export const hardReload = tabMethod(
|
||||
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
|
||||
"desktop.ipc.preview.hardReload",
|
||||
(manager, tabId) => manager.hardReload(tabId),
|
||||
);
|
||||
export const openDevTools = tabMethod(
|
||||
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
|
||||
"desktop.ipc.preview.openDevTools",
|
||||
(manager, tabId) => manager.openDevTools(tabId),
|
||||
);
|
||||
export const cancelPickElement = tabMethod(
|
||||
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
|
||||
"desktop.ipc.preview.cancelPickElement",
|
||||
(manager, tabId) => manager.cancelPickElement(tabId),
|
||||
);
|
||||
export const startRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
|
||||
"desktop.ipc.preview.startRecording",
|
||||
(manager, tabId) => manager.startRecording(tabId),
|
||||
);
|
||||
export const stopRecording = tabMethod(
|
||||
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
|
||||
"desktop.ipc.preview.stopRecording",
|
||||
(manager, tabId) => manager.stopRecording(tabId),
|
||||
);
|
||||
|
||||
export const clearCookies = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCookies();
|
||||
}),
|
||||
});
|
||||
|
||||
export const clearCache = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.clearCache();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getPreviewConfig = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
|
||||
payload: DesktopPreviewConfigInputSchema,
|
||||
result: DesktopPreviewWebviewConfigSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.getBrowserSession(environmentId);
|
||||
return {
|
||||
partition: yield* manager.getBrowserPartition(environmentId),
|
||||
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
|
||||
preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
|
||||
payload: DesktopPreviewAnnotationThemeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.setAnnotationTheme(theme);
|
||||
}),
|
||||
});
|
||||
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const captureScreenshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: DesktopPreviewScreenshotArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.captureScreenshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const revealArtifact = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.revealArtifact(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
|
||||
payload: DesktopPreviewArtifactInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.copyArtifactToClipboard(path);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationStatus = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationStatus,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationStatus(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationSnapshot = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: PreviewAutomationSnapshot,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationSnapshot(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationClick = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
|
||||
payload: DesktopPreviewAutomationClickInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationClick(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationType = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationTypeInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationType(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationPress = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
|
||||
payload: DesktopPreviewAutomationPressInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationPress(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationScroll = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
|
||||
payload: DesktopPreviewAutomationScrollInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationScroll(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationEvaluate = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
|
||||
payload: DesktopPreviewAutomationEvaluateInputSchema,
|
||||
result: Schema.Unknown,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.automationEvaluate(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const automationWaitFor = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
|
||||
payload: DesktopPreviewAutomationWaitForInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.automationWaitFor(tabId, input);
|
||||
}),
|
||||
});
|
||||
|
||||
export const saveRecording = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
|
||||
payload: DesktopPreviewRecordingSaveInputSchema,
|
||||
result: DesktopPreviewRecordingArtifactSchema,
|
||||
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.saveRecording(tabId, mimeType, data);
|
||||
}),
|
||||
});
|
||||
|
||||
export const methods = [
|
||||
createTab,
|
||||
closeTab,
|
||||
registerWebview,
|
||||
navigate,
|
||||
goBack,
|
||||
goForward,
|
||||
refresh,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
resetZoom,
|
||||
hardReload,
|
||||
openDevTools,
|
||||
clearCookies,
|
||||
clearCache,
|
||||
getPreviewConfig,
|
||||
setAnnotationTheme,
|
||||
pickElement,
|
||||
cancelPickElement,
|
||||
captureScreenshot,
|
||||
revealArtifact,
|
||||
copyArtifactToClipboard,
|
||||
automationStatus,
|
||||
automationSnapshot,
|
||||
automationClick,
|
||||
automationType,
|
||||
automationPress,
|
||||
automationScroll,
|
||||
automationEvaluate,
|
||||
automationWaitFor,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
saveRecording,
|
||||
] as const;
|
||||
@@ -1,76 +0,0 @@
|
||||
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
|
||||
const NonBlankString = Schema.String.check(
|
||||
Schema.makeFilter((value) =>
|
||||
value.trim().length > 0 ? undefined : "Expected a non-empty string",
|
||||
),
|
||||
);
|
||||
|
||||
const SetSavedEnvironmentSecretInput = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
secret: NonBlankString,
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: SavedEnvironmentRegistryPayload,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.getRegistry;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentRegistry = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
|
||||
payload: SavedEnvironmentRegistryPayload,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry(records);
|
||||
}),
|
||||
});
|
||||
|
||||
export const getSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.NullOr(Schema.String),
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
|
||||
}),
|
||||
});
|
||||
|
||||
export const setSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: SetSavedEnvironmentSecretInput,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
|
||||
environmentId,
|
||||
secret,
|
||||
}) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
return yield* savedEnvironments.setSecret({
|
||||
environmentId,
|
||||
secret,
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export const removeSavedEnvironmentSecret = makeIpcMethod({
|
||||
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
payload: EnvironmentId,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.removeSecret(environmentId);
|
||||
}),
|
||||
});
|
||||
Loaded 100 of 2190 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user