Compare commits
364
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
565106d333 | ||
|
|
9ee21b09ac | ||
|
|
30e6d8838c | ||
|
|
c9063f03ea | ||
|
|
1add47b322 | ||
|
|
80991402dc | ||
|
|
1a6599437b | ||
|
|
184d8ef33b | ||
|
|
038560e580 | ||
|
|
21a3669cee | ||
|
|
b3b4b57794 | ||
|
|
6ae44b418a | ||
|
|
4a2f8b04bb | ||
|
|
8f9ab0845d | ||
|
|
baaeda305c | ||
|
|
7e01d33f0e | ||
|
|
9fd788b5a9 | ||
|
|
710fd0eeb3 | ||
|
|
e15f655ba4 | ||
|
|
59be6f7846 | ||
|
|
5304f3e9d4 | ||
|
|
85389b9883 | ||
|
|
db1507e986 | ||
|
|
96bfa67b3d | ||
|
|
5ff3a03ada | ||
|
|
23d45d914e | ||
|
|
bad1143b02 | ||
|
|
92d4a2e996 | ||
|
|
2fab18e289 | ||
|
|
1b16ed663f | ||
|
|
83ad26c3a3 | ||
|
|
fd51561b4e | ||
|
|
9e201941aa | ||
|
|
2ab188f1c0 | ||
|
|
9513e62e24 | ||
|
|
97db94c9bf | ||
|
|
5015d7cf9f | ||
|
|
df19f6cfe3 | ||
|
|
6bc6cb6be4 | ||
|
|
1e59b4c400 | ||
|
|
33f9705926 | ||
|
|
da6253b3dd | ||
|
|
ac1264e2ca | ||
|
|
2eb099fdc8 | ||
|
|
b28f9bf0a1 | ||
|
|
d0b8d6306b | ||
|
|
9666b87516 | ||
|
|
e3a9c2518d | ||
|
|
18918d1c4d | ||
|
|
8d24b5131f | ||
|
|
770946d026 | ||
|
|
8601797233 | ||
|
|
b73232bdd3 | ||
|
|
f131228a59 | ||
|
|
e321667b10 | ||
|
|
849bac8946 | ||
|
|
6fd088af9f | ||
|
|
b54bfc9312 | ||
|
|
e1378a1f4d | ||
|
|
5a84614809 | ||
|
|
63e6faef62 | ||
|
|
d37a9b09b8 | ||
|
|
560d4a4560 | ||
|
|
52e5a75a87 | ||
|
|
c196f422ed | ||
|
|
f0b57ca231 | ||
|
|
2db08457f2 | ||
|
|
083fa4ab24 | ||
|
|
35172010b1 | ||
|
|
57b1052679 | ||
|
|
1e355a2a34 | ||
|
|
44621c345f | ||
|
|
220e573b14 | ||
|
|
6befe42eb0 | ||
|
|
b30a9bc414 | ||
|
|
ac4780f451 | ||
|
|
3da7f9c5c3 | ||
|
|
c842c6f5b9 | ||
|
|
6676f9c83b | ||
|
|
65b005f1e4 | ||
|
|
752acbf654 | ||
|
|
f5fce74169 | ||
|
|
9c7622dac3 | ||
|
|
c14bcca103 | ||
|
|
1fa315ea93 | ||
|
|
f9730979c1 | ||
|
|
59d0c922e9 | ||
|
|
2ea51bd31f | ||
|
|
e5c82d79a0 | ||
|
|
9afef94a61 | ||
|
|
a7b0366cbe | ||
|
|
428d9f9f67 | ||
|
|
1b120f352f | ||
|
|
0a7c662d39 | ||
|
|
b91a000a17 | ||
|
|
8de0aa24d9 | ||
|
|
cad2c93616 | ||
|
|
78f462c4e1 | ||
|
|
3b72d17cbc | ||
|
|
d440442db6 | ||
|
|
67ef189d8b | ||
|
|
fbcae59ef5 | ||
|
|
9821bca1ce | ||
|
|
3d74474f6c | ||
|
|
f0e2975180 | ||
|
|
d43210050b | ||
|
|
ef051bdb87 | ||
|
|
0ca9fb3fb5 | ||
|
|
cbd55d6374 | ||
|
|
96906805f1 | ||
|
|
73b2e8fdd4 | ||
|
|
5da45337f7 | ||
|
|
f21d5e444e | ||
|
|
9a1472d955 | ||
|
|
2abe66800c | ||
|
|
0d38866dcf | ||
|
|
f993fa1c5f | ||
|
|
83d769f02d | ||
|
|
c8ad4b8135 | ||
|
|
bd18d8d6d1 | ||
|
|
659986ce38 | ||
|
|
062b4618c2 | ||
|
|
deb901d638 | ||
|
|
02f4ce5667 | ||
|
|
285cf5947b | ||
|
|
1a003e383a | ||
|
|
963ebf5bd7 | ||
|
|
ba9c9ae81d | ||
|
|
076e9048dc | ||
|
|
05eb051184 | ||
|
|
ddaa6afef5 | ||
|
|
6f69b4407f | ||
|
|
6dbffa022d | ||
|
|
5bb8c03664 | ||
|
|
886195ec1e | ||
|
|
288d8e3457 | ||
|
|
5208bdeb0d | ||
|
|
a6c9b41f90 | ||
|
|
70c423a5e4 | ||
|
|
89c320df0b | ||
|
|
7b2cf4374f | ||
|
|
49964e38c0 | ||
|
|
e70cdb478d | ||
|
|
be01b287b9 | ||
|
|
c2f8cb7ca1 | ||
|
|
89ee692bf0 | ||
|
|
a20923ce46 | ||
|
|
8101cd0449 | ||
|
|
30164cb1ba | ||
|
|
0640410726 | ||
|
|
2c7267ad43 | ||
|
|
daf8ee0b2f | ||
|
|
ed886fe181 | ||
|
|
4eaf5ef8bb | ||
|
|
0de9540739 | ||
|
|
31891a1a0c | ||
|
|
45d9aa90ba | ||
|
|
7a84f6cf10 | ||
|
|
f0fb406acf | ||
|
|
82406bce99 | ||
|
|
72d673a855 | ||
|
|
e2cd2383ce | ||
|
|
5661c6116c | ||
|
|
6d70e6d778 | ||
|
|
be1a836745 | ||
|
|
239ef1c54d | ||
|
|
61b51ae0e3 | ||
|
|
bfc69e4b4d | ||
|
|
af281c9fc4 | ||
|
|
bd422fd8d1 | ||
|
|
33a03c8a7b | ||
|
|
a17459e8a9 | ||
|
|
b2ee17d7c1 | ||
|
|
7963cc70f3 | ||
|
|
b792ed9f7b | ||
|
|
2e66b1fdfc | ||
|
|
8100062a78 | ||
|
|
a1762fdd74 | ||
|
|
388b43a27c | ||
|
|
23f0a1ae38 | ||
|
|
85b1734d4d | ||
|
|
3ffe84f968 | ||
|
|
220efad62b | ||
|
|
b98a0f0d22 | ||
|
|
95305c36fa | ||
|
|
48aa875c0e | ||
|
|
a8cd2ad2eb | ||
|
|
4a07c1ca9d | ||
|
|
cf5c9948c8 | ||
|
|
2288d416aa | ||
|
|
ddfe45c66e | ||
|
|
9547cf2463 | ||
|
|
1c7d059f55 | ||
|
|
6fa4576078 | ||
|
|
ae7b27de82 | ||
|
|
6b73b3defe | ||
|
|
7aad7911f6 | ||
|
|
6da92244cc | ||
|
|
c471145e96 | ||
|
|
64a991ad45 | ||
|
|
0ec4fbc4a3 | ||
|
|
ea50b695a7 | ||
|
|
331c6dce7f | ||
|
|
4f5834ba72 | ||
|
|
aa16c180e5 | ||
|
|
470d4eb993 | ||
|
|
99d91ddaa4 | ||
|
|
ab3b55e29a | ||
|
|
e4abc31f1e | ||
|
|
b7d1981b57 | ||
|
|
64a3cd6d7d | ||
|
|
48e2c27f2f | ||
|
|
8b2ea5721a | ||
|
|
df2f1273e9 | ||
|
|
f9e8236899 | ||
|
|
8f341f20c9 | ||
|
|
808d685355 | ||
|
|
80720ad592 | ||
|
|
a483337a02 | ||
|
|
1ffba7093a | ||
|
|
3da315e7b5 | ||
|
|
a2ca89aa10 | ||
|
|
990bb0b689 | ||
|
|
7251f1a1f1 | ||
|
|
30e471530b | ||
|
|
de592a00e8 | ||
|
|
2a04db134c | ||
|
|
37d3667de4 | ||
|
|
9697b765e5 | ||
|
|
9d9a872bcc | ||
|
|
9235c83eb7 | ||
|
|
e0c85a20ef | ||
|
|
3c5bdb84a9 | ||
|
|
70de6e1786 | ||
|
|
47dfc65265 | ||
|
|
41ebf22eea | ||
|
|
3d429662c9 | ||
|
|
7b38fb5c6b | ||
|
|
7537adc30f | ||
|
|
94696b0f54 | ||
|
|
fff6a5b028 | ||
|
|
da6e1a9678 | ||
|
|
8eca20005b | ||
|
|
2fa1fec8d8 | ||
|
|
9bd2a4c688 | ||
|
|
4fb03aff0b | ||
|
|
d7950ac153 | ||
|
|
36caf34c68 | ||
|
|
90e3778660 | ||
|
|
94331c58ec | ||
|
|
c30a6d9b99 | ||
|
|
37ae1abbe9 | ||
|
|
82b76e2138 | ||
|
|
8a16cadbaf | ||
|
|
2b1d4fecb8 | ||
|
|
cec1bb9de3 | ||
|
|
25ec0b9d13 | ||
|
|
966cc05a90 | ||
|
|
1cbd88aba0 | ||
|
|
553867262c | ||
|
|
11639bf439 | ||
|
|
a261a6440a | ||
|
|
6f04a5cffb | ||
|
|
30c9622806 | ||
|
|
69dfb7f09a | ||
|
|
e60821f0e0 | ||
|
|
64bf016191 | ||
|
|
5192f777fe | ||
|
|
283c7ac4ba | ||
|
|
78eb3ecae9 | ||
|
|
d3037064e6 | ||
|
|
0ad91b6e7f | ||
|
|
ca72e381c6 | ||
|
|
491219bf1f | ||
|
|
e5c7547067 | ||
|
|
bfc31507f8 | ||
|
|
03adf215ce | ||
|
|
916cff733c | ||
|
|
a041981276 | ||
|
|
964cc27901 | ||
|
|
acf761b2f5 | ||
|
|
ab8182cb4e | ||
|
|
ef4ec2ad4b | ||
|
|
61514c1294 | ||
|
|
894d6d68f5 | ||
|
|
fccec9f097 | ||
|
|
50a3d6b872 | ||
|
|
e259dd23c7 | ||
|
|
df78cda8bf | ||
|
|
605c2bb734 | ||
|
|
cb11a71d63 | ||
|
|
41124c7260 | ||
|
|
b0b275227b | ||
|
|
cb293fe790 | ||
|
|
1d694dcbd8 | ||
|
|
32407df9c5 | ||
|
|
162e774294 | ||
|
|
063ed7120a | ||
|
|
34b15a9ace | ||
|
|
fbecb7365e | ||
|
|
4029b858ea | ||
|
|
5b2577f6a9 | ||
|
|
bc142f84a2 | ||
|
|
e4829603ff | ||
|
|
1d77cec991 | ||
|
|
4ba4871af7 | ||
|
|
edc503a7a8 | ||
|
|
323dc321a2 | ||
|
|
6154b46cb8 | ||
|
|
abc409c2d4 | ||
|
|
1877237c7a | ||
|
|
e0513d2983 | ||
|
|
9dd425b223 | ||
|
|
50871eb5de | ||
|
|
4b71a2ae2f | ||
|
|
197d348711 | ||
|
|
5c9358acaa | ||
|
|
cbe8052020 | ||
|
|
69a18ce912 | ||
|
|
f0c6ba9946 | ||
|
|
90f3913a81 | ||
|
|
2652fee49b | ||
|
|
2f466ffc9c | ||
|
|
9146ed2f49 | ||
|
|
f0f16e4f6e | ||
|
|
00da6b57a4 | ||
|
|
6ab2f16809 | ||
|
|
6efcf3e10c | ||
|
|
748203ea19 | ||
|
|
b125b76351 | ||
|
|
758decaa56 | ||
|
|
2d9066e089 | ||
|
|
35a684000d | ||
|
|
9e3e9bb4f0 | ||
|
|
a8e05cbb92 | ||
|
|
e6987965f6 | ||
|
|
fc28abf24b | ||
|
|
85a8986870 | ||
|
|
faea70aeba | ||
|
|
d19039aeef | ||
|
|
49c0d96edf | ||
|
|
3137c2b162 | ||
|
|
c3e8fb67d7 | ||
|
|
72b960fa39 | ||
|
|
08e4932f04 | ||
|
|
1b4830ff06 | ||
|
|
694f8d1c6e | ||
|
|
1b61ce1112 | ||
|
|
60af905e70 | ||
|
|
8650f05f95 | ||
|
|
8fe8f9a9c1 | ||
|
|
936593c258 | ||
|
|
2919147c80 | ||
|
|
1ba3d01bc6 | ||
|
|
5fcdefd057 | ||
|
|
38a6e3ce65 | ||
|
|
f2d2fb2f24 | ||
|
|
8829e2f9b9 | ||
|
|
2deea7abb0 | ||
|
|
b64ae880e0 | ||
|
|
887dd6e455 | ||
|
|
f1a68ac9b0 | ||
|
|
55dd01612e | ||
|
|
3c50a64885 |
No files matched your search
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
@@ -50,24 +50,13 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
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.
|
||||
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
|
||||
|
||||
```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. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ Use these client origins:
|
||||
- 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.
|
||||
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to 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
|
||||
|
||||
@@ -125,31 +125,29 @@ Do not start, stop, erase, or reconfigure an emulator owned by another task. Tra
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
Use the bundled helper from the repository root. It issues a fresh credential against the running backend's exact base directory, opens the existing Add Environment route with the credential in an encoded query parameter, and asks that route to connect once:
|
||||
|
||||
```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>
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
ios <simulator-udid> <server-port> <base-dir>
|
||||
|
||||
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
|
||||
android <emulator-serial> <server-port> <base-dir>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
Run only the command for the selected platform. The helper uses `http://127.0.0.1:<server-port>` for iOS and `http://10.0.2.2:<server-port>` for Android. Pass a fifth argument only when testing a non-development URL scheme.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
The helper opens this registered route:
|
||||
|
||||
```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
|
||||
```text
|
||||
t3code-dev://connections/new?pairingUrl=<encoded-pairing-url>&autoConnect=1
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
The Add Environment route owns the behavior: `pairingUrl` prefills its normal host and token inputs, while `autoConnect=1` submits once in development builds and returns to Home after success. Without `autoConnect`, the same route only prefills the form for manual inspection.
|
||||
|
||||
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.
|
||||
Do not enter pairing hosts or tokens through simulator keyboard automation. Xcode's semantic typer sends HID-style key events through the simulator's active keyboard state, which can corrupt uppercase tokens and punctuation even when the host Mac uses a U.S. input source. The one-shot route is the deterministic pairing path. Use the visible form only as a fallback, and paste credentials rather than typing them character by character.
|
||||
|
||||
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.
|
||||
|
||||
@@ -183,6 +181,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor
|
||||
- **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.
|
||||
- **The pairing form opens but does not connect:** confirm the deep link uses the existing `connections/new` route, includes `autoConnect=1`, and carries a freshly minted encoded `pairingUrl`.
|
||||
- **Pairing text changes case or punctuation:** do not retry semantic typing. Use `scripts/pair-client.sh`; the simulator keyboard layout and HID input path are not reliable for credentials.
|
||||
- **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.
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 <ios|android> <device-id> <server-port> <base-dir> [url-scheme]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[[ $# -ge 4 && $# -le 5 ]] || usage
|
||||
|
||||
platform="$1"
|
||||
device_id="$2"
|
||||
server_port="$3"
|
||||
base_dir="$4"
|
||||
url_scheme="${5:-t3code-dev}"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
mobile_origin="http://127.0.0.1:${server_port}"
|
||||
;;
|
||||
android)
|
||||
mobile_origin="http://10.0.2.2:${server_port}"
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
|
||||
repo_root="$(git rev-parse --show-toplevel)"
|
||||
cd "$repo_root"
|
||||
|
||||
if ! pairing_output="$({
|
||||
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-${device_id:0:8}"
|
||||
} 2>&1)"; then
|
||||
echo "Could not mint a mobile pairing credential." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
pairing_url="$(printf '%s\n' "$pairing_output" | sed -n 's/^Pair URL: //p' | tail -n 1)"
|
||||
if [[ -z "$pairing_url" ]]; then
|
||||
echo "Could not parse the mobile pairing URL." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
deep_link="$(PAIRING_URL="$pairing_url" URL_SCHEME="$url_scheme" node - <<'NODE'
|
||||
const query = new URLSearchParams({
|
||||
pairingUrl: process.env.PAIRING_URL,
|
||||
autoConnect: "1",
|
||||
});
|
||||
process.stdout.write(`${process.env.URL_SCHEME}://connections/new?${query}`);
|
||||
NODE
|
||||
)"
|
||||
|
||||
case "$platform" in
|
||||
ios)
|
||||
xcrun simctl openurl "$device_id" "$deep_link"
|
||||
;;
|
||||
android)
|
||||
# adb shell re-joins its arguments and evaluates them through the device
|
||||
# shell, so the deep link's `?`/`&` must be quoted once more for that shell.
|
||||
adb -s "$device_id" shell \
|
||||
"am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \
|
||||
>/dev/null
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "Opened the existing Add Environment route with a fresh pairing credential."
|
||||
+12
-9
@@ -1,12 +1,14 @@
|
||||
# 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.
|
||||
# `cp .env.example .env` enables T3 Connect against the production deployment.
|
||||
# These are the same public identifiers baked into official release builds, not
|
||||
# secrets. Remove or comment them out to build with cloud features disabled.
|
||||
# Do not add server-side secrets to this file.
|
||||
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
|
||||
# under API keys, JWT templates, and OAuth applications.
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
|
||||
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
|
||||
|
||||
# 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
|
||||
@@ -15,8 +17,9 @@
|
||||
# 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
|
||||
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
|
||||
# automatically.
|
||||
T3CODE_RELAY_URL=https://relay.t3.codes
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -30,6 +30,7 @@ body:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
# Keep entries sorted alphabetically.
|
||||
github:adityavardhansharma
|
||||
github:binbandit
|
||||
github:chrisdeeming
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:gbarros-dev
|
||||
github:gfsaaser24
|
||||
github:github-actions[bot]
|
||||
github:hwanseoc
|
||||
github:jamesx0416
|
||||
@@ -25,7 +27,9 @@ github:Noojuno
|
||||
github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:saphid
|
||||
github:shiroyasha9
|
||||
github:StiensWout
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
@@ -33,3 +37,5 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
github:bil0000
|
||||
@@ -0,0 +1,429 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const ARTIFACT_NAME = "thread-transfer-results";
|
||||
const RESULT_FILE = "thread-transfer-result.json";
|
||||
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
|
||||
const PROVIDERS = ["codex", "claudeAgent"];
|
||||
const OBSERVED_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"threadSnapshotDecodedBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const CEILING_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const SCENARIO_KEYS = [
|
||||
"id",
|
||||
"historyTurns",
|
||||
"historyCommandToolsPerTurn",
|
||||
"historyMcpResultBytes",
|
||||
"measuredCommandTools",
|
||||
"measuredMcpResultBytes",
|
||||
];
|
||||
|
||||
function resultShaMarker(sha) {
|
||||
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
|
||||
}
|
||||
|
||||
function assertObject(value, label) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error(`${label} must be an object`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertExactKeys(value, expected, label) {
|
||||
assertObject(value, label);
|
||||
const actual = Object.keys(value).sort();
|
||||
const wanted = [...expected].sort();
|
||||
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
|
||||
throw new Error(`${label} has unexpected fields`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertMetric(value, label) {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
|
||||
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateResult(value) {
|
||||
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
|
||||
if (value.schemaVersion !== 1) {
|
||||
throw new Error("result.schemaVersion must be 1");
|
||||
}
|
||||
|
||||
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
|
||||
if (value.scenario.id !== "thread-transfer-v1") {
|
||||
throw new Error("result.scenario.id is not supported");
|
||||
}
|
||||
for (const key of SCENARIO_KEYS.slice(1)) {
|
||||
assertMetric(value.scenario[key], `result.scenario.${key}`);
|
||||
}
|
||||
|
||||
assertExactKeys(value.providers, PROVIDERS, "result.providers");
|
||||
for (const provider of PROVIDERS) {
|
||||
const entry = value.providers[provider];
|
||||
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
|
||||
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
|
||||
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
|
||||
for (const key of OBSERVED_KEYS) {
|
||||
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
|
||||
}
|
||||
for (const key of CEILING_KEYS) {
|
||||
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function readResult(directory) {
|
||||
if (!directory) return undefined;
|
||||
const file = path.join(directory, RESULT_FILE);
|
||||
if (!fs.existsSync(file)) return undefined;
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.size > 64 * 1_024) {
|
||||
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
|
||||
}
|
||||
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (bytes < 1_024) return `${bytes} B`;
|
||||
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
|
||||
return `${(bytes / 1_024).toFixed(1)} KiB`;
|
||||
}
|
||||
|
||||
function formatValue(value, kind) {
|
||||
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
|
||||
}
|
||||
|
||||
function formatImpact(current, baseline, kind) {
|
||||
if (baseline === undefined) return "—";
|
||||
const delta = current - baseline;
|
||||
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
|
||||
const magnitude = formatValue(Math.abs(delta), kind);
|
||||
const percent =
|
||||
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
|
||||
return `${prefix}${magnitude}${percent}`;
|
||||
}
|
||||
|
||||
function sameScenario(left, right) {
|
||||
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
|
||||
}
|
||||
|
||||
const METRICS = [
|
||||
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
|
||||
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
|
||||
{
|
||||
key: "measuredTurnWebSocketWireBytes",
|
||||
label: "Live turn WebSocket wire",
|
||||
kind: "bytes",
|
||||
},
|
||||
{
|
||||
key: "measuredTurnWebSocketDecodedBytes",
|
||||
label: "Live turn WebSocket decoded",
|
||||
kind: "bytes",
|
||||
},
|
||||
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
|
||||
];
|
||||
|
||||
function renderComment(input) {
|
||||
const current = input.current;
|
||||
const baseline = input.baseline;
|
||||
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
|
||||
const rows = [];
|
||||
const ceilingChanges = [];
|
||||
let failed = false;
|
||||
|
||||
for (const provider of PROVIDERS) {
|
||||
for (const metric of METRICS) {
|
||||
const observed = current.providers[provider].observed[metric.key];
|
||||
const ceiling = current.providers[provider].ceiling[metric.key];
|
||||
const baselineObserved = comparable
|
||||
? baseline.providers[provider].observed[metric.key]
|
||||
: undefined;
|
||||
const pass = observed <= ceiling;
|
||||
failed ||= !pass;
|
||||
rows.push(
|
||||
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
|
||||
);
|
||||
|
||||
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
|
||||
ceilingChanges.push(
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const baselineLink = input.baselineRun
|
||||
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
|
||||
: "unavailable";
|
||||
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
|
||||
const notices = [];
|
||||
if (!baseline) {
|
||||
notices.push(
|
||||
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
|
||||
);
|
||||
} else if (!comparable) {
|
||||
notices.push(
|
||||
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
|
||||
);
|
||||
} else if (!input.baselineRun.matchesBase) {
|
||||
notices.push(
|
||||
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
|
||||
);
|
||||
}
|
||||
if (ceilingChanges.length > 0) {
|
||||
notices.push(
|
||||
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
COMMENT_MARKER,
|
||||
resultShaMarker(input.currentRun.sha),
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
failed
|
||||
? "❌ One or more thread transfer ceilings were exceeded."
|
||||
: "✅ Thread transfer remains within every enforced ceiling.",
|
||||
...(notices.length > 0 ? ["", ...notices] : []),
|
||||
"",
|
||||
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
|
||||
...rows,
|
||||
"",
|
||||
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
|
||||
"",
|
||||
"<details>",
|
||||
"<summary>Scenario and decoded snapshot size</summary>",
|
||||
"",
|
||||
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
|
||||
"",
|
||||
...PROVIDERS.map(
|
||||
(provider) =>
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
|
||||
),
|
||||
"",
|
||||
"</details>",
|
||||
"",
|
||||
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function artifactsForRun(github, owner, repo, runId) {
|
||||
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
|
||||
owner,
|
||||
repo,
|
||||
run_id: runId,
|
||||
per_page: 100,
|
||||
});
|
||||
}
|
||||
|
||||
function findResultArtifact(artifacts) {
|
||||
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
|
||||
}
|
||||
|
||||
async function resolve({ github, context, core }) {
|
||||
const source = context.payload.workflow_run;
|
||||
const { owner, repo } = context.repo;
|
||||
if (source.event !== "pull_request") {
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
let pullNumber = source.pull_requests?.[0]?.number;
|
||||
if (!pullNumber) {
|
||||
const associated = await github.paginate(
|
||||
github.rest.repos.listPullRequestsAssociatedWithCommit,
|
||||
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
|
||||
);
|
||||
const matchingPulls = associated.filter(
|
||||
(pull) =>
|
||||
pull.state === "open" &&
|
||||
pull.head.sha === source.head_sha &&
|
||||
pull.head.ref === source.head_branch,
|
||||
);
|
||||
if (matchingPulls.length !== 1) {
|
||||
core.info(
|
||||
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
|
||||
);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
pullNumber = matchingPulls[0].number;
|
||||
}
|
||||
if (!pullNumber) {
|
||||
core.info("No open pull request is associated with the completed CI run.");
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
|
||||
if (pull.head.sha !== source.head_sha) {
|
||||
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
|
||||
const sourceArtifact = findResultArtifact(sourceArtifacts);
|
||||
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: source.workflow_id,
|
||||
branch: pull.base.ref,
|
||||
event: "push",
|
||||
status: "success",
|
||||
per_page: 100,
|
||||
});
|
||||
const orderedRuns = [
|
||||
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
|
||||
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
|
||||
].slice(0, 20);
|
||||
|
||||
let baselineRun;
|
||||
for (const run of orderedRuns) {
|
||||
const artifacts = await artifactsForRun(github, owner, repo, run.id);
|
||||
if (findResultArtifact(artifacts)) {
|
||||
baselineRun = run;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput("publish", "true");
|
||||
core.setOutput("pull_number", String(pullNumber));
|
||||
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
|
||||
core.setOutput("pr_run_id", String(source.id));
|
||||
core.setOutput("pr_sha", source.head_sha);
|
||||
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
|
||||
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
|
||||
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
|
||||
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
|
||||
core.setOutput(
|
||||
"baseline_matches_base",
|
||||
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
|
||||
);
|
||||
}
|
||||
|
||||
async function upsertComment(github, context, pullNumber, body, options = {}) {
|
||||
const { owner, repo } = context.repo;
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: pullNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find(
|
||||
(comment) =>
|
||||
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
|
||||
);
|
||||
if (
|
||||
options.preserveResultSha &&
|
||||
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
|
||||
} else {
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
expectedSha,
|
||||
body,
|
||||
options,
|
||||
) {
|
||||
const { owner, repo } = context.repo;
|
||||
const { data: pull } = await github.rest.pulls.get({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: pullNumber,
|
||||
});
|
||||
if (pull.head.sha !== expectedSha) {
|
||||
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
await upsertComment(github, context, pullNumber, body, options);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function publish({ github, context, core }) {
|
||||
const pullNumber = Number(process.env.PR_NUMBER);
|
||||
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
|
||||
throw new Error("PR_NUMBER is invalid");
|
||||
}
|
||||
|
||||
const current = readResult(process.env.PR_RESULT_DIR);
|
||||
const currentRun = {
|
||||
sha: process.env.PR_SHA,
|
||||
conclusion: process.env.PR_CONCLUSION,
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
|
||||
};
|
||||
if (!current) {
|
||||
await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
[
|
||||
COMMENT_MARKER,
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
|
||||
"",
|
||||
"_This comment will update automatically after the next completed run._",
|
||||
].join("\n"),
|
||||
{ preserveResultSha: currentRun.sha },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
|
||||
const baselineRun = baseline
|
||||
? {
|
||||
sha: process.env.BASELINE_SHA,
|
||||
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
|
||||
}
|
||||
: undefined;
|
||||
const body = renderComment({ current, baseline, currentRun, baselineRun });
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
body,
|
||||
);
|
||||
if (published) {
|
||||
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
publish,
|
||||
readResult,
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
};
|
||||
@@ -0,0 +1,292 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
|
||||
const {
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
} = require("./thread-transfer-report.cjs");
|
||||
|
||||
function result(overrides = {}) {
|
||||
const observed = {
|
||||
totalWireBytes: 2_200_000,
|
||||
threadSnapshotWireBytes: 1_950_000,
|
||||
threadSnapshotDecodedBytes: 9_100_000,
|
||||
measuredTurnWebSocketWireBytes: 250_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_150_000,
|
||||
measuredTurnWebSocketMessages: 15,
|
||||
};
|
||||
const ceiling = {
|
||||
totalWireBytes: 2_900_000,
|
||||
threadSnapshotWireBytes: 2_600_000,
|
||||
measuredTurnWebSocketWireBytes: 320_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_550_000,
|
||||
measuredTurnWebSocketMessages: 20,
|
||||
};
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: 10,
|
||||
historyCommandToolsPerTurn: 5,
|
||||
historyMcpResultBytes: 900_000,
|
||||
measuredCommandTools: 20,
|
||||
measuredMcpResultBytes: 1_100_000,
|
||||
},
|
||||
providers: {
|
||||
codex: { observed: { ...observed, ...overrides }, ceiling },
|
||||
claudeAgent: { observed, ceiling },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("validates the fixed artifact schema", () => {
|
||||
assert.equal(validateResult(result()).schemaVersion, 1);
|
||||
assert.throws(
|
||||
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
|
||||
/unexpected fields/,
|
||||
);
|
||||
assert.throws(
|
||||
() => validateResult(result({ totalWireBytes: "lots" })),
|
||||
/non-negative safe integer/,
|
||||
);
|
||||
});
|
||||
|
||||
test("renders baseline, impact, ceiling, and ceiling changes", () => {
|
||||
const baseline = result();
|
||||
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
|
||||
current.providers.codex.ceiling = {
|
||||
...current.providers.codex.ceiling,
|
||||
measuredTurnWebSocketWireBytes: 330_000,
|
||||
};
|
||||
const comment = renderComment({
|
||||
current,
|
||||
baseline,
|
||||
currentRun: {
|
||||
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
conclusion: "success",
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
|
||||
},
|
||||
baselineRun: {
|
||||
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
matchesBase: true,
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
|
||||
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
|
||||
assert.match(comment, /This PR changes transfer ceilings/);
|
||||
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
|
||||
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
|
||||
assert.match(
|
||||
comment,
|
||||
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
|
||||
const outputs = {};
|
||||
const listWorkflowRunArtifacts = () => {};
|
||||
const listWorkflowRuns = () => {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
const github = {
|
||||
paginate: async (method, input) => {
|
||||
if (method === listPullRequestsAssociatedWithCommit) {
|
||||
return [
|
||||
{
|
||||
number: 5350,
|
||||
state: "open",
|
||||
head: { sha: "head-sha", ref: "feature-branch", repo: null },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRunArtifacts) {
|
||||
return [
|
||||
{
|
||||
name: "thread-transfer-results",
|
||||
expired: false,
|
||||
runId: input.run_id,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRuns) {
|
||||
return [{ id: 1, head_sha: "base-sha" }];
|
||||
}
|
||||
throw new Error("unexpected pagination call");
|
||||
},
|
||||
rest: {
|
||||
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
|
||||
pulls: {
|
||||
get: async () => ({
|
||||
data: {
|
||||
head: { sha: "head-sha" },
|
||||
base: { sha: "base-sha", ref: "main" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
};
|
||||
await resolve({
|
||||
github,
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "true");
|
||||
assert.equal(outputs.pull_number, "5350");
|
||||
assert.equal(outputs.pr_artifact, "true");
|
||||
assert.equal(outputs.baseline_run_id, "1");
|
||||
assert.equal(outputs.baseline_matches_base, "true");
|
||||
});
|
||||
|
||||
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
|
||||
const outputs = {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
let fetchedPull = false;
|
||||
await resolve({
|
||||
github: {
|
||||
paginate: async (method) => {
|
||||
assert.equal(method, listPullRequestsAssociatedWithCommit);
|
||||
return [5350, 5351].map((number) => ({
|
||||
number,
|
||||
state: "open",
|
||||
head: {
|
||||
sha: "head-sha",
|
||||
ref: "feature-branch",
|
||||
repo: { full_name: "pingdotgg/t3code" },
|
||||
},
|
||||
}));
|
||||
},
|
||||
rest: {
|
||||
actions: {},
|
||||
pulls: {
|
||||
get: async () => {
|
||||
fetchedPull = true;
|
||||
},
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
},
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "false");
|
||||
assert.equal(fetchedPull, false);
|
||||
});
|
||||
|
||||
test("does not publish a stale result after the PR head advances", async () => {
|
||||
let listedComments = false;
|
||||
const info = [];
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => {
|
||||
listedComments = true;
|
||||
return [];
|
||||
},
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
throw new Error("must not create a stale comment");
|
||||
},
|
||||
updateComment: () => {
|
||||
throw new Error("must not update a stale comment");
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: (message) => info.push(message) },
|
||||
5350,
|
||||
"old-head-sha",
|
||||
"stale body",
|
||||
);
|
||||
|
||||
assert.equal(published, false);
|
||||
assert.equal(listedComments, false);
|
||||
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
|
||||
});
|
||||
|
||||
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
|
||||
let updatedComment = false;
|
||||
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => [
|
||||
{
|
||||
id: 1,
|
||||
user: { login: "github-actions[bot]" },
|
||||
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
|
||||
},
|
||||
],
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
updateComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: () => {} },
|
||||
5350,
|
||||
sha,
|
||||
"missing artifact warning",
|
||||
{ preserveResultSha: sha },
|
||||
);
|
||||
|
||||
assert.equal(published, true);
|
||||
assert.equal(updatedComment, false);
|
||||
});
|
||||
@@ -6,6 +6,10 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.event.pull_request.number || github.sha }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
@@ -14,6 +18,11 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -22,6 +31,11 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -31,6 +45,9 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -47,6 +64,11 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -55,26 +77,60 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
|
||||
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
|
||||
run: vp run test
|
||||
|
||||
- name: Publish transfer budget report
|
||||
if: always()
|
||||
run: |
|
||||
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
|
||||
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
|
||||
else
|
||||
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
- name: Upload thread transfer result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer-result.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
runs-on: blacksmith-6vcpu-macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Install mobile native static analysis tools
|
||||
run: brew bundle install --file apps/mobile/Brewfile
|
||||
@@ -89,13 +145,20 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -38,13 +38,20 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
|
||||
@@ -2,13 +2,18 @@ name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
types: [opened, reopened, synchronize, labeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
if: |
|
||||
contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
concurrency:
|
||||
group: mobile-eas-preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
@@ -34,6 +39,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
@@ -41,7 +50,9 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
|
||||
@@ -5,6 +5,25 @@ name: Mobile EAS Production
|
||||
# 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.
|
||||
#
|
||||
# Every merge to main that touches the mobile app reconciles, per platform:
|
||||
# 1. Store builds: if the latest production build's version differs from
|
||||
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
|
||||
# track). Bumping `version` is therefore all it takes to
|
||||
# start the next release train — the first build of a version enters
|
||||
# external-TestFlight beta review immediately, and later builds of the
|
||||
# same version auto-approve until that version is released. After App
|
||||
# Store approval, Apple closes the release train and `version` must be
|
||||
# bumped before another iOS build can be submitted. Releasing to the App
|
||||
# Store stays a manual App Store Connect step.
|
||||
# 2. OTA: publish a production-channel update for each platform where at
|
||||
# least one finished production build matches the current native
|
||||
# fingerprint. Old-version binaries with a matching fingerprint receive
|
||||
# it too. When native drift means no binary could install the update,
|
||||
# it is skipped and flagged in the job summary instead of published
|
||||
# into the void.
|
||||
# workflow_dispatch remains as a manual override for both modes (e.g. to
|
||||
# retry an errored build or force an OTA).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -25,14 +44,38 @@ on:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
version:
|
||||
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
|
||||
required: false
|
||||
type: string
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-eas-production.yml
|
||||
|
||||
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
|
||||
# queued run per group, so a burst of merges collapses into one run of the
|
||||
# newest commit — intermediate commits don't need their own OTA.
|
||||
concurrency:
|
||||
group: mobile-eas-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -52,11 +95,25 @@ jobs:
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- id: version_app_token
|
||||
name: Mint release app token for version override
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.version_app_token.outputs.token || github.token }}
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
# when the partial clone can't serve the unfetched blobs.
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
@@ -64,7 +121,9 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
@@ -92,15 +151,74 @@ jobs:
|
||||
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'
|
||||
- name: Apply manual version override
|
||||
if: steps.version_app_token.outcome == 'success'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
|
||||
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
|
||||
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node --input-type=module -e '
|
||||
import fs from "node:fs";
|
||||
const path = "apps/mobile/app.config.ts";
|
||||
const source = fs.readFileSync(path, "utf8");
|
||||
const next = source.replace(
|
||||
/^( version: ")[^"]+(".*)$/m,
|
||||
`$1${process.env.RELEASE_VERSION}$2`,
|
||||
);
|
||||
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
|
||||
throw new Error("Could not update app version");
|
||||
}
|
||||
fs.writeFileSync(path, next);
|
||||
'
|
||||
vp fmt apps/mobile/app.config.ts
|
||||
|
||||
if git diff --quiet -- apps/mobile/app.config.ts; then
|
||||
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
git config user.name "${APP_SLUG}[bot]"
|
||||
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
|
||||
git add apps/mobile/app.config.ts
|
||||
git commit \
|
||||
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
|
||||
-m "Co-authored-by: codex <[email protected]>"
|
||||
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
|
||||
|
||||
- name: Summarize manual build version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
{
|
||||
echo "## Manual production build"
|
||||
echo
|
||||
echo "- App version: \`$version\`"
|
||||
echo "- Platform: \`${{ inputs.platform }}\`"
|
||||
echo
|
||||
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Build and submit (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && 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'
|
||||
- name: Publish OTA update (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -111,3 +229,62 @@ jobs:
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
|
||||
# No --status filter on build:list: an in-queue/in-progress build must
|
||||
# count as existing, or every merge during the build window would cut a
|
||||
# duplicate. After an errored build, retry via workflow_dispatch
|
||||
# mode=build — pushes won't re-trigger it until the app version changes.
|
||||
- id: store_builds
|
||||
name: Ensure store builds exist for the current app version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
failed=0
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
for platform in ios android; do
|
||||
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
|
||||
if [ "$latest" = "$version" ]; then
|
||||
echo "$platform: production build for $version already exists (or is in progress)"
|
||||
continue
|
||||
fi
|
||||
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
|
||||
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
failed=1
|
||||
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Publish fingerprint-gated OTA
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
|
||||
for platform in ios android; do
|
||||
# eas-cli prints an environment-loaded notice to stdout before the
|
||||
# JSON even with --json, so discard everything before the document.
|
||||
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
|
||||
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
|
||||
if [ "$matching" -gt 0 ]; then
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform "$platform" \
|
||||
--message "$message" \
|
||||
--non-interactive
|
||||
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Propagate store build failure
|
||||
if: steps.store_builds.outcome == 'failure'
|
||||
run: exit 1
|
||||
@@ -0,0 +1,205 @@
|
||||
name: Mobile Fingerprint Check
|
||||
|
||||
# Detects whether a PR changes the native fingerprint — i.e. whether merging
|
||||
# it would leave main un-OTA-able until a new store build ships. Native-change
|
||||
# PRs get the "📱 Native Change" label so they can be held and merged as a
|
||||
# batch right before the next store submission, keeping main OTA-able for
|
||||
# everything else in between. (Once one native PR merges, every later merge
|
||||
# inherits the drifted fingerprint and loses OTA reach too — that is why the
|
||||
# signal has to fire before merge, not after.)
|
||||
#
|
||||
# The check is advisory: it always passes, the label is the signal. Both
|
||||
# fingerprints are computed in this one job (same OS, same corepack-pinned
|
||||
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-fingerprint-check.yml
|
||||
|
||||
concurrency:
|
||||
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fingerprint:
|
||||
name: Native fingerprint diff
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# Default pull_request checkout is the merge commit (PR applied on
|
||||
# top of base), so the "head" fingerprint is the state main would
|
||||
# actually be in after merging — stale branches compare cleanly.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- 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: Fingerprint merge result
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
|
||||
done
|
||||
|
||||
- name: Fingerprint base
|
||||
run: |
|
||||
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
|
||||
# Re-sync node_modules to the base commit's lockfile before
|
||||
# fingerprinting — a dep-changing PR must not fingerprint the base
|
||||
# against head's installed packages.
|
||||
pnpm install --filter=@t3tools/mobile...
|
||||
cd apps/mobile
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
|
||||
done
|
||||
|
||||
- id: compare
|
||||
name: Compare fingerprints
|
||||
run: |
|
||||
changed=""
|
||||
{
|
||||
echo "## Native fingerprint diff"
|
||||
echo
|
||||
for platform in ios android; do
|
||||
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
|
||||
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
|
||||
if [ "$head_hash" = "$base_hash" ]; then
|
||||
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
|
||||
continue
|
||||
fi
|
||||
changed="$changed $platform"
|
||||
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
|
||||
jq -r -n \
|
||||
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
|
||||
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
|
||||
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
|
||||
| $h[0].sources[]
|
||||
| select($bm[(.filePath // .id)] != .hash)
|
||||
| " - \(.type): `\(.filePath // .id)`"'
|
||||
done
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Sync native change label
|
||||
# Fork PRs get a read-only token under pull_request; the check stays
|
||||
# advisory there (summary only). This workflow must not move to
|
||||
# pull_request_target — it installs and runs PR code.
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabel = {
|
||||
name: "📱 Native Change",
|
||||
color: "d93f0b",
|
||||
description:
|
||||
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
|
||||
};
|
||||
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== managedLabel.color ||
|
||||
(existing.description ?? "") !== managedLabel.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
|
||||
|
||||
if (nativeChanged && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [managedLabel.name],
|
||||
});
|
||||
} else if (!nativeChanged && hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
|
||||
);
|
||||
@@ -37,13 +37,22 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
@@ -77,13 +86,22 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
|
||||
+106
-17
@@ -38,6 +38,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
@@ -84,6 +88,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -192,6 +200,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -269,14 +281,19 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3...
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
@@ -326,21 +343,29 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -351,14 +376,26 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/desktop...
|
||||
- --filter=t3...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -598,6 +635,19 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -605,6 +655,13 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -624,6 +681,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -659,6 +720,24 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
@@ -667,20 +746,18 @@ jobs:
|
||||
needs: [preflight, build, publish_cli]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -740,7 +817,7 @@ jobs:
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -757,11 +834,11 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
token: ${{ github.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -777,7 +854,7 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
token: ${{ github.token }}
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
@@ -802,6 +879,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
@@ -916,6 +997,10 @@ jobs:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
persist-credentials: true
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- id: app_bot
|
||||
name: Resolve GitHub App bot identity
|
||||
@@ -986,6 +1071,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Thread Transfer Report
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish PR comment
|
||||
if: github.event.workflow_run.event == 'pull_request'
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# workflow_run has a write-capable token even for fork PRs. Only load the
|
||||
# publisher from the trusted default branch and never execute PR code.
|
||||
- name: Checkout trusted publisher
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
- name: Test trusted publisher
|
||||
run: node --test .github/scripts/thread-transfer-report.test.cjs
|
||||
|
||||
- id: resolve
|
||||
name: Resolve PR and baseline artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.resolve({ github, context, core });
|
||||
|
||||
- name: Download PR result
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/pr
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
|
||||
- name: Download main baseline
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/main
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
|
||||
- name: Update thread transfer comment
|
||||
if: steps.resolve.outputs.publish == 'true'
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
|
||||
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
|
||||
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
|
||||
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
|
||||
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
|
||||
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
|
||||
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.publish({ github, context, core });
|
||||
@@ -0,0 +1,132 @@
|
||||
name: Web Preview
|
||||
|
||||
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
|
||||
# that push and every subsequent push. The deployment is a plain (non-prod,
|
||||
# non-aliased) deploy into the existing hosted-web Vercel project, so the
|
||||
# latest/nightly channel aliases are never touched.
|
||||
#
|
||||
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
|
||||
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
|
||||
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
|
||||
# backend) and open the pairing URL against the preview origin.
|
||||
#
|
||||
# The preview must be opened at the exact deployment URL from the PR comment.
|
||||
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
|
||||
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
|
||||
# self-identify as the hosted app.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: web-preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy web preview
|
||||
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
|
||||
# workflow should skip rather than fail for them. On `labeled` events, only
|
||||
# the preview label itself triggers a deploy.
|
||||
if: >-
|
||||
github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- id: deploy
|
||||
name: Deploy preview
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
|
||||
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
|
||||
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--yes \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
--scope "$vercel_scope"
|
||||
)"
|
||||
|
||||
echo "Deployed $deployment_url"
|
||||
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Comment deployment URL
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
with:
|
||||
script: |
|
||||
const marker = "<!-- web-preview-deploy -->";
|
||||
const body = [
|
||||
marker,
|
||||
"### Web preview",
|
||||
"",
|
||||
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
|
||||
"",
|
||||
"Open this exact URL — the hosted-app origin is baked in at build time.",
|
||||
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
|
||||
"code under Settings → Connections.",
|
||||
].join("\n");
|
||||
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find((comment) => comment.body?.includes(marker));
|
||||
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
body,
|
||||
});
|
||||
}
|
||||
@@ -30,6 +30,7 @@ dist-electron/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
# Worktree Management v1
|
||||
|
||||
## Problem
|
||||
|
||||
t3code creates a worktree per thread (`~/.t3/worktrees/<project>/t3code-<hash>`, branch
|
||||
`t3code/<8hex>`) but has almost no lifecycle management. With the settled system, threads
|
||||
are rarely deleted anymore, so worktrees accumulate unboundedly (real case: 186 worktrees).
|
||||
|
||||
Current state:
|
||||
|
||||
- No worktree registry. A worktree exists only as the denormalized `worktree_path` column on
|
||||
`projection_threads` (`apps/server/src/persistence/Layers/ProjectionThreads.ts:41`). Nothing
|
||||
records creation time, last use, or dirty state.
|
||||
- The only cleanup path is the interactive "delete worktree too?" dialog when deleting the
|
||||
last thread that uses one (`apps/web/src/hooks/useThreadActions.ts:253-397`). It is
|
||||
desktop-only (requires `localApi`), so web users always leak worktrees. `thread.delete`
|
||||
on the server never touches the worktree (`apps/server/src/orchestration/decider.ts:381-401`).
|
||||
- `git worktree prune` is never invoked anywhere.
|
||||
- Settling (`settled_override`/`settled_at`) is a projection-level soft-hide; it has no effect
|
||||
on the worktree, so settled threads pin their worktrees forever.
|
||||
- Checkpoint refs (`refs/t3/checkpoints/...`) live in the shared ref store, not in the
|
||||
worktree's private git dir, so removing a worktree does not lose checkpoints. Branches are
|
||||
likewise repo-level. This is what makes lossless revival possible.
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
1. **Worktrees only in v1.** No branch deletion, no checkpoint-ref GC. Branches are cheap and
|
||||
keeping them makes revival trivial. Merged-branch cleanup can be a later tier.
|
||||
2. **No safety-snapshot-before-delete.** Auto-prune only ever touches *safe* worktrees. Users
|
||||
may force-delete a dirty worktree, but the UI must make clear that this is destructive and
|
||||
the uncommitted state cannot be restored later — that's on them.
|
||||
3. **Never auto-prune dirty worktrees.** Instead, surface them in the Worktrees settings page
|
||||
as "needs attention": e.g. *"This worktree has had no activity for N days, but has
|
||||
uncommitted changes so it won't be deleted automatically."*
|
||||
4. **Global policy settings only.** Per-project overrides are an application-wide capability
|
||||
we don't have yet; out of scope.
|
||||
5. **Orphan handling is configurable.** A setting chooses whether orphaned worktrees (no
|
||||
thread references them) are deleted immediately when they become orphaned, or just fall
|
||||
under the normal inactivity schedule.
|
||||
6. **CLI is a stretch goal and must be super minimal** (`t3 worktrees list` / `prune`), or
|
||||
dropped from v1 entirely.
|
||||
|
||||
## Definitions
|
||||
|
||||
**Worktree record** (derived, not persisted): for each entry in `git worktree list --porcelain`
|
||||
under the project's worktrees dir, joined against thread rows sharing that normalized path:
|
||||
|
||||
- `path`, `branch`
|
||||
- linked threads: id, title, effective settled state, deleted state
|
||||
- `dirty` (working-tree changes, via existing `localStatus` — `GitManager.ts:856-864`)
|
||||
- `unpushed` (`aheadCount` / `aheadOfDefaultCount` / `hasUpstream` via `remoteStatus`)
|
||||
- `prState` (merged / open / none, already available on the remote status result)
|
||||
- `lastActivity`: max of linked threads' last activity / `settled_at`; fallback to worktree
|
||||
dir mtime for orphans
|
||||
- `orphaned`: no non-deleted thread references the path
|
||||
- `safeToPrune`: see below
|
||||
|
||||
**Safe to prune** = ALL of:
|
||||
|
||||
- no *active* (unsettled, undeleted) thread references the worktree
|
||||
- working tree clean
|
||||
- branch merged, or fully pushed (`hasUpstream && aheadCount == 0`), or contains no commits
|
||||
beyond its recorded merge-base (`aheadOfDefaultCount == 0`)
|
||||
- path is inside the managed worktrees dir and is not the project `workspaceRoot`
|
||||
|
||||
**Auto-prunable** = safeToPrune AND (orphaned with "delete orphans immediately" enabled, OR
|
||||
`lastActivity` older than the configured inactivity window).
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Worktree inventory service (server)
|
||||
|
||||
New Effect service (e.g. `apps/server/src/vcs/WorktreeInventory.ts`) that produces the derived
|
||||
records above per project. Scan via `git worktree list --porcelain` (driver already parses
|
||||
this at `GitVcsDriverCore.ts:2121-2164` for branch annotation — extract/reuse). Status via
|
||||
existing `GitManager.localStatus`/`remoteStatus` (already ~1s cached). Short TTL cache on the
|
||||
assembled inventory; a full status sweep across 186 worktrees is not free, so statuses should
|
||||
be fetched lazily/batched and the settings page should render the list first and stream
|
||||
status in.
|
||||
|
||||
Exposed over WS RPC alongside the existing `vcsCreateWorktree`/`vcsRemoveWorktree`
|
||||
(`apps/server/src/ws.ts:1838-1849`): `vcsListWorktrees` (inventory) and
|
||||
`vcsPruneWorktrees` (bulk delete of a provided safe set, server re-validates safety before
|
||||
each removal — never trust the client's classification).
|
||||
|
||||
### 2. Worktrees settings page (web)
|
||||
|
||||
Follow the appearance-settings pattern:
|
||||
|
||||
- route `apps/web/src/routes/settings.worktrees.tsx`
|
||||
- `WorktreesSettingsPanel` in `apps/web/src/components/settings/SettingsPanels.tsx`
|
||||
- nav entry + path union in `apps/web/src/components/settings/SettingsSidebarNav.tsx:26-49`
|
||||
|
||||
Content:
|
||||
|
||||
- List of managed worktrees with badges: dirty, unpushed, merged, orphaned, settled-only,
|
||||
linked-thread count. Sort: needs-attention first, then by lastActivity ascending.
|
||||
- "Needs attention" grouping for dirty-but-inactive worktrees with the explanatory copy from
|
||||
decision 3.
|
||||
- Filtering (client-side over the loaded inventory — no new RPC surface):
|
||||
- free-text search matching branch name, directory name, and linked thread titles
|
||||
- project filter (the page is global; with several projects the list interleaves otherwise)
|
||||
- status filter chips, multi-select: needs attention / safe to prune / dirty / unpushed /
|
||||
orphaned / settled-only
|
||||
- the bulk "Prune N safe worktrees" action operates on the *filtered* set when filters are
|
||||
active, and the button label must reflect that (e.g. "Prune 12 safe worktrees (filtered)")
|
||||
- filter state is ephemeral (not persisted) in v1
|
||||
- Row actions: delete (safe rows: plain confirm; dirty/unpushed rows: destructive-styled
|
||||
confirm spelling out that uncommitted changes / unpushed commits are permanently lost).
|
||||
- Bulk action: "Prune N safe worktrees".
|
||||
- Policy controls (global):
|
||||
- auto-prune enabled on/off
|
||||
- inactivity window: 7 / 14 (default) / 30 days
|
||||
- "delete orphaned worktrees immediately" toggle
|
||||
- Deleting never deletes threads; threads keep their `branch`/`worktreePath` metadata for
|
||||
revival.
|
||||
|
||||
Open implementation question: where the policy settings persist. The sweep runs server-side,
|
||||
so the policy must be server-readable — unlike e.g. `sidebarAutoSettleAfterDays`, which is a
|
||||
client-side setting (`BetaSettingsPanel.tsx:12-14`). Resolve during implementation: either an
|
||||
existing server-persisted settings mechanism if one exists, or a small server settings
|
||||
store + RPC.
|
||||
|
||||
### 3. Auto-prune sweep (server)
|
||||
|
||||
Periodic loop on the `ProviderSessionReaper` pattern
|
||||
(`apps/server/src/provider/Layers/ProviderSessionReaper.ts:106-131` — `Effect.forkScoped` +
|
||||
`Schedule.spaced`), started from `serverRuntimeStartup.ts` like the reaper (`:345`). Cadence:
|
||||
hourly-ish; exact interval is uninteresting as long as it also runs once shortly after startup.
|
||||
|
||||
Each sweep, per project: build inventory → remove auto-prunable worktrees via existing
|
||||
`removeWorktree` (`GitVcsDriverCore.ts:2393-2405`, without `--force` — a non-forced
|
||||
`git worktree remove` refusing due to unexpected dirt is a desirable last-line safety net) →
|
||||
finish with `git worktree prune` (new driver op) to clear stale admin entries. Log a concise
|
||||
summary event/line of what was removed and what was skipped-with-reason (feeds the
|
||||
"needs attention" UI).
|
||||
|
||||
Also handle decision 5's immediate mode: when `thread.delete` orphans a worktree and the
|
||||
"delete orphans immediately" setting is on, the server removes it (if safe) without any
|
||||
client dialog — this replaces the desktop-only prompt path as the mechanism; the web/desktop
|
||||
delete flow keeps its dialog purely as UX when the setting is off.
|
||||
|
||||
### 4. Revival on unsettle
|
||||
|
||||
When a thread becomes active again (explicit unsettle, or the existing auto-unsettle-on-
|
||||
activity in `decider.ts:785-799` etc.) — or when a turn starts — and its `worktreePath` no
|
||||
longer exists on disk: recreate it in `bootstrap.prepareWorktree` (`ws.ts:1011-1041`) via
|
||||
`git worktree add <path> <branch>` on the thread's existing branch (branch always survives
|
||||
v1 pruning). If the branch is somehow gone (user deleted it manually), fail with a clear
|
||||
error offering to recreate from the base branch. Checkpoint refs survive pruning, so
|
||||
diff/revert history remains intact after revival.
|
||||
|
||||
### 5. Minimal CLI (stretch)
|
||||
|
||||
`t3 worktrees list` (table from the inventory) and `t3 worktrees prune [--dry-run]`
|
||||
(safe set only; no force flag in v1). New file in `apps/server/src/cli/`, patterned on
|
||||
`project.ts`. Cut first if v1 needs trimming — the settings page's bulk prune covers the
|
||||
acute 186-worktree cleanup.
|
||||
|
||||
## Build order
|
||||
|
||||
1. Inventory service + `vcsListWorktrees`/`vcsPruneWorktrees` RPC
|
||||
2. Worktrees settings page (observability + manual/bulk delete) — solves the acute pain
|
||||
3. Policy settings + auto-prune sweep + orphan-immediate handling + server-side removal on
|
||||
thread delete
|
||||
4. Revival on missing worktree
|
||||
5. CLI (stretch)
|
||||
|
||||
## Out of scope for v1
|
||||
|
||||
- Branch deletion / checkpoint-ref GC
|
||||
- Safety snapshots of dirty state before deletion
|
||||
- Per-project policy overrides
|
||||
- Any migration/backfill beyond what the inventory naturally surfaces (existing orphans just
|
||||
show up as prunable)
|
||||
@@ -1,52 +1,147 @@
|
||||
# AGENTS.md
|
||||
# T3 Code
|
||||
|
||||
## Task Completion Requirements
|
||||
T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs (Codex, Claude Code, Cursor, Grok, OpenCode) and serves web, desktop, and mobile clients.
|
||||
|
||||
- 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.
|
||||
You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor.
|
||||
|
||||
## Dev Servers
|
||||
## What makes T3 Code special?
|
||||
|
||||
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
|
||||
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
|
||||
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
|
||||
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
|
||||
We have over 100,000 users who love T3 Code. It's important we maintain the things they love as we continue to iterate on the product. Here's a brief list of the things we can never compromise on.
|
||||
|
||||
## Package Roles
|
||||
### 1. Open at the core
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and client applications. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
- `packages/client-runtime`: Shared runtime package for sharing client code across web and mobile.
|
||||
T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way.
|
||||
|
||||
## Reference Repos
|
||||
### 2. Performance without compromise
|
||||
|
||||
- Open-source Codex repo: https://github.com/openai/codex
|
||||
Lots of apps have gotten bogged down with bad tech decisions and "slop". We have not, and we're proud of the performance of T3 Code. We regularly audit for performance regressions, often caused by sending too much data over websockets, css animations causing gpu spikes, lists being hard to render, and more. Make sure all changes are considerate of performance impact.
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
### 3. Remote ready
|
||||
|
||||
## Vendored Repositories
|
||||
The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported.
|
||||
|
||||
This project vendors external repositories under `.repos/` as read-only reference material for coding
|
||||
agents.
|
||||
### 4. Multi-surface
|
||||
|
||||
- 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 `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
|
||||
examples of idiomatic usage, tests, module structure, and API design.
|
||||
- When writing relay infrastructure code with Alchemy, inspect `.repos/alchemy-effect/` for examples of
|
||||
idiomatic usage, tests, module structure, and API design.
|
||||
T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
|
||||
|
||||
**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `npx t3` command. Both need to be supported by all new features where reasonable.
|
||||
|
||||
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
|
||||
|
||||
**Mobile** is a React Native app for both iOS and Android, available on the App Store and Google Play. The mobile app allows for connecting to any T3 Code server to control work remotely.
|
||||
|
||||
## A note from Theo
|
||||
|
||||
I like ambitious ideas, simple systems, and software that feels obvious. Do not preserve complexity just because it already exists. Do not introduce machinery because it looks architecturally impressive. Understand the real constraint, then fight for the smallest model that makes the correct behavior unsurprising.
|
||||
|
||||
Channel both "measure twice, cut once" and "yagni". Fight scope creep. Try to honor the dev's intent in both a minimal and realistic fashion.
|
||||
|
||||
The rest of this document is meant to help you navigate the codebase and make changes effectively. Think of these instructions less as "hard rules", more as "good defaults". The developer's preferences should be able to override anything here.
|
||||
|
||||
Of note: Most T3 Code contributions will come from T3 Code itself, often controlled remotely. This means you should be careful about accessing data, killing dev servers, and other things that may damage the T3 Code instance that the contributor is using.
|
||||
|
||||
## A small glossary
|
||||
|
||||
We need to be on the same page with terminology. When communicating, use this language:
|
||||
|
||||
- **you** means the agent reading this file and changing T3 Code.
|
||||
- **we, us, and maintainers** mean Theo, Julius and the people building T3 Code. These are who you are talking to now.
|
||||
- **user** means the person using T3 Code to direct coding agents.
|
||||
- **agent** means the coding agent a user runs inside T3 Code. Depending on context, that may also include you.
|
||||
- **provider** means the agent runtime or harness T3 Code talks to, such as Codex, Claude, Cursor, or OpenCode.
|
||||
- **client** means the web, desktop, or mobile UI.
|
||||
- **environment** means one running T3 server and the machine, filesystem, provider credentials, and state it owns.
|
||||
- **project** means an environment-local workspace record rooted at a directory.
|
||||
- **thread** means the durable conversation and work history for a project.
|
||||
- **turn** means one user-to-agent cycle, including follow-up work such as checkpointing.
|
||||
- **T3 home** means the base data directory. Runtime state normally lives below its userdata directory.
|
||||
|
||||
## The three ways to hurt yourself
|
||||
|
||||
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
|
||||
2. **Writing to the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Reading it and copying from it are fine, and a good way to get real test data (see Test data). Never start a server against it, never open it read-write, never clean it up.
|
||||
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
|
||||
|
||||
## Hit every surface
|
||||
|
||||
The most common defect in this repo is a change that works on the path you tested and is missing everywhere else. Before calling frontend work done, walk this list and say which entries applied:
|
||||
|
||||
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
|
||||
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
|
||||
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
|
||||
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
|
||||
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
|
||||
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
|
||||
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
|
||||
|
||||
## Dev servers
|
||||
|
||||
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
|
||||
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
|
||||
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
|
||||
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
|
||||
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
|
||||
- Stop what you started, by the PID you tracked. See rule 1.
|
||||
|
||||
## Test data
|
||||
|
||||
An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state:
|
||||
|
||||
- Copy from `~/.t3/userdata` (the developer's real data, the most realistic test set) or `~/.t3/dev`. Worktree state lives at `<worktree>/.t3/userdata`.
|
||||
- Snapshot the database with `VACUUM INTO`, which is safe even while a server has the source open and yields one consistent file:
|
||||
|
||||
```bash
|
||||
mkdir -p .t3/userdata
|
||||
rm -f .t3/userdata/state.sqlite* # VACUUM INTO refuses to overwrite
|
||||
bun -e "new (require('bun:sqlite').Database)(process.env.HOME + '/.t3/userdata/state.sqlite', { readonly: true }).run(\"VACUUM INTO '.t3/userdata/state.sqlite'\")"
|
||||
```
|
||||
|
||||
A plain `cp` is only safe when no server has the source open, and must bring the `-wal` and `-shm` siblings along. A live file copy is a corrupt copy.
|
||||
|
||||
- Bring `secrets` and `settings.json` only if the flow under test needs them.
|
||||
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
|
||||
|
||||
## Verifying
|
||||
|
||||
- Smallest proof that the change works. `vp test run <files>` for the tests you touched, targeted lint and typecheck for the scope you changed.
|
||||
- **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
|
||||
- Backend behavior changes ship with focused tests for that behavior.
|
||||
- The server is event-sourced and its async flows emit typed receipts. Wait on receipts and worker drains, never on sleeps or polling. A test that needs a timeout to pass is wrong.
|
||||
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Never make a PR unless the developer explicitly asks you to do so.
|
||||
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
|
||||
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
|
||||
- UI changes need before/after images. Motion or timing needs a short video.
|
||||
- One concern per PR. If the description says "also", split it.
|
||||
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
|
||||
|
||||
## How it works
|
||||
|
||||
Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore.
|
||||
|
||||
Full glossary with file links: `docs/internals/glossary.md`
|
||||
|
||||
## Where code lives
|
||||
|
||||
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
|
||||
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
|
||||
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
|
||||
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
|
||||
- `packages/client-runtime` - client code shared by web and mobile.
|
||||
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
|
||||
|
||||
## Taste
|
||||
|
||||
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
|
||||
- Inferred types over annotations. `any` is the enemy.
|
||||
- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior.
|
||||
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
|
||||
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
|
||||
|
||||
## Additional tips
|
||||
|
||||
- Don't verify with browsers or computer use unless the user explicitly agrees or requests it.
|
||||
- Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features.
|
||||
@@ -1,24 +1,36 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
|
||||
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
|
||||
|
||||
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
|
||||
|
||||
## "Wait, what are you selling me?"
|
||||
|
||||
Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar.
|
||||
|
||||
We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the editor that you want.
|
||||
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
> T3 Code currently supports Codex, Claude, Cursor, Grok Build and OpenCode. Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
|
||||
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login`
|
||||
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
|
||||
### Run without installing
|
||||
### Try it out (install-free)
|
||||
|
||||
The easiest way to test T3 Code is to run the server in your terminal (requires Node.js 22.16+, 23.11+, or 24.10+):
|
||||
|
||||
```bash
|
||||
npx t3@latest
|
||||
```
|
||||
|
||||
This will launch T3 Code's backend on your machine as well as the local web app to control your agents.
|
||||
|
||||
Tip: Use `npx t3@latest --help` for the full CLI reference.
|
||||
|
||||
### Desktop app
|
||||
@@ -47,19 +59,23 @@ yay -S t3code-bin
|
||||
|
||||
We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
|
||||
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Remote access](./docs/user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
- [Reference](./docs/reference/encyclopedia.md)
|
||||
Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
|
||||
- [Install and first run](./docs/user/install.md)
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
|
||||
- Linux: [run T3 Code as a background service](./docs/user/background-service.md)
|
||||
|
||||
Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md).
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.29",
|
||||
"version": "0.0.33",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
@@ -17,7 +18,9 @@ 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 DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
yield* shellEnvironment.installIntoProcess;
|
||||
const hasCommandLinePasswordStore =
|
||||
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
|
||||
const linuxElectronOptions =
|
||||
environment.platform === "linux" && !hasCommandLinePasswordStore
|
||||
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
|
||||
: preReadyElectronOptions.linux;
|
||||
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
|
||||
if (
|
||||
linuxElectronOptions.passwordStore !== null ||
|
||||
preReadyElectronOptions.linux?.passwordStore !== null
|
||||
) {
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
}
|
||||
if (linuxElectronOptions.passwordStore !== null) {
|
||||
yield* electronApp.appendCommandLineSwitch(
|
||||
"password-store",
|
||||
linuxElectronOptions.passwordStore,
|
||||
);
|
||||
}
|
||||
}
|
||||
const userDataPath = yield* appIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
|
||||
yield* desktopSettings.load;
|
||||
|
||||
if (environment.platform === "linux") {
|
||||
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
|
||||
if (linuxElectronOptions !== null) {
|
||||
yield* logStartupInfo("linux password store configured", {
|
||||
passwordStore: hasCommandLinePasswordStore
|
||||
? "command-line"
|
||||
: (linuxElectronOptions.passwordStore ?? "electron-default"),
|
||||
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
|
||||
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
yield* appIdentity.configure;
|
||||
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
|
||||
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
|
||||
);
|
||||
yield* logStartupInfo("app ready");
|
||||
if (environment.platform === "linux") {
|
||||
const selectedBackend = yield* safeStorage.selectedStorageBackend;
|
||||
yield* logStartupInfo("safe storage ready", {
|
||||
backend: Option.getOrElse(selectedBackend, () => "unknown"),
|
||||
});
|
||||
}
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
calls.setAboutPanelOptions.push(options);
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
: Option.none();
|
||||
};
|
||||
|
||||
export const resolveUserDataPath = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
|
||||
return commitHash;
|
||||
});
|
||||
|
||||
const resolveUserDataPath = Effect.gen(function* () {
|
||||
const legacyPath = environment.path.join(
|
||||
environment.appDataDirectory,
|
||||
environment.legacyUserDataDirName,
|
||||
);
|
||||
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopUserDataPathResolutionError({
|
||||
legacyPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyPathExists
|
||||
? legacyPath
|
||||
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
|
||||
const userDataPath = resolveUserDataPath.pipe(
|
||||
Effect.provide(
|
||||
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
|
||||
),
|
||||
);
|
||||
|
||||
const configure = Effect.gen(function* () {
|
||||
const commitHash = yield* resolveAboutCommitHash;
|
||||
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
|
||||
|
||||
return DesktopAppIdentity.of({
|
||||
resolveUserDataPath,
|
||||
resolveUserDataPath: userDataPath,
|
||||
configure,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
|
||||
storage: storageMock,
|
||||
}));
|
||||
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const makeDesktopClerkLayer = (isDevelopment = true) => {
|
||||
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
|
||||
const environment = DesktopEnvironment.DesktopEnvironment.of({
|
||||
stateDir: "/tmp/t3-state",
|
||||
isDevelopment,
|
||||
appDataDirectory: "/tmp/app-data",
|
||||
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
|
||||
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const electronApp = {
|
||||
setPath: (name: string, value: string) =>
|
||||
Effect.sync(() => {
|
||||
events.push(`setPath:${name}:${value}`);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
|
||||
return DesktopClerk.layer.pipe(
|
||||
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Layer.succeed(ElectronApp.ElectronApp, electronApp),
|
||||
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
|
||||
|
||||
it.effect("acquires and releases the SDK bridge with the layer", () => {
|
||||
const cleanup = vi.fn();
|
||||
const events: string[] = [];
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup });
|
||||
createClerkBridgeMock.mockImplementation(() => {
|
||||
events.push("createClerkBridge");
|
||||
return { cleanup, isPrimaryInstance: true };
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
|
||||
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
|
||||
|
||||
assert.deepEqual(createClerkBridgeMock.mock.calls, [
|
||||
[
|
||||
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
|
||||
],
|
||||
]);
|
||||
assert.equal(cleanup.mock.calls.length, 1);
|
||||
// The bridge acquires Electron's single-instance lock at creation, and
|
||||
// the lock both lives in and creates the userData directory — so the
|
||||
// real path must be set before the bridge exists.
|
||||
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
|
||||
storageMock.mockClear();
|
||||
createClerkBridgeMock.mockClear();
|
||||
});
|
||||
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("registers the second-instance handler in the primary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.isSuccess(exit));
|
||||
assert.equal(quit.mock.calls.length, 0);
|
||||
assert.deepEqual(registeredEvents, ["second-instance"]);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("quits and interrupts startup in a secondary instance", () => {
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
|
||||
const quit = vi.fn();
|
||||
const registeredEvents: string[] = [];
|
||||
const electronApp = {
|
||||
quit: Effect.sync(quit),
|
||||
on: (eventName: string) =>
|
||||
Effect.sync(() => {
|
||||
registeredEvents.push(eventName);
|
||||
}),
|
||||
} as unknown as ElectronApp.ElectronApp["Service"];
|
||||
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
|
||||
|
||||
assert.isTrue(Exit.hasInterrupts(exit));
|
||||
assert.equal(quit.mock.calls.length, 1);
|
||||
assert.deepEqual(registeredEvents, []);
|
||||
}).pipe(
|
||||
Effect.provide(makeDesktopClerkLayer()),
|
||||
Effect.provideService(ElectronApp.ElectronApp, electronApp),
|
||||
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
|
||||
);
|
||||
});
|
||||
|
||||
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() };
|
||||
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
|
||||
storageMock.mockReturnValue(storageAdapter);
|
||||
createClerkBridgeMock.mockReturnValue(bridge);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
|
||||
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
yield* Effect.acquireRelease(
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
|
||||
// Electron scopes the single-instance lock to the userData directory and
|
||||
// creates that directory when the lock is acquired. The SDK bridge takes
|
||||
// the lock at creation, so userData must already point at the real
|
||||
// directory here — under the default productName-derived path, acquiring
|
||||
// the lock would create "T3 Code (Alpha)" and make the legacy-install
|
||||
// detection in resolveUserDataPath match on fresh installs.
|
||||
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
|
||||
const bridge = yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
|
||||
catch: (cause) =>
|
||||
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
|
||||
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
if (!(yield* electronApp.requestSingleInstanceLock)) {
|
||||
// The SDK bridge holds Electron's single-instance lock (acquired at
|
||||
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
|
||||
// forwarded to the running app. In a secondary instance the bridge has
|
||||
// already begun quitting the app; app.quit() is asynchronous, so stop
|
||||
// bootstrap here before whenReady can fire.
|
||||
if (!bridge.isPrimaryInstance) {
|
||||
yield* electronApp.quit;
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
|
||||
export const DesktopConfig = Config.all({
|
||||
appDataDirectory: trimmedString("APPDATA"),
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
xdgDataHome: trimmedString("XDG_DATA_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
|
||||
import * as NodePath from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
resolveEarlyLinuxElectronOptions,
|
||||
resolveEarlyLinuxPasswordStorePreference,
|
||||
} from "./DesktopEarlyElectronStartup.ts";
|
||||
|
||||
describe("DesktopEarlyElectronStartup", () => {
|
||||
const joinPath = NodePath.posix.join;
|
||||
|
||||
it("reads the persisted linux password-store preference before Electron is ready", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("accepts JSONC in the early desktop settings file", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => `{
|
||||
// manually edited setting
|
||||
"linuxPasswordStore": "gnome-libsecret",
|
||||
}`,
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
|
||||
it("falls back to auto when the early settings document is missing or invalid", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => {
|
||||
throw new Error("missing");
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "auto");
|
||||
});
|
||||
|
||||
it("preserves absolute root paths when resolving early settings", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("resolves the early linux Electron switches", () => {
|
||||
const options = resolveEarlyLinuxElectronOptions({
|
||||
env: {
|
||||
T3CODE_HOME: "/home/user/.t3-test",
|
||||
XDG_CURRENT_DESKTOP: "niri",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "auto" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(options, {
|
||||
linuxWmClass: "t3code-dev",
|
||||
passwordStore: "gnome-libsecret",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet");
|
||||
});
|
||||
|
||||
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
T3CODE_HOME: " ",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import {
|
||||
resolveDesktopBaseDir,
|
||||
resolveDesktopStateDir,
|
||||
type JoinPath,
|
||||
} from "./DesktopStatePaths.ts";
|
||||
|
||||
interface EarlyDesktopSettingsInput {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly readFileString: (path: string) => string;
|
||||
}
|
||||
|
||||
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
|
||||
|
||||
export interface EarlyLinuxElectronOptions {
|
||||
readonly linuxWmClass: string;
|
||||
readonly passwordStore: LinuxPasswordStoreSwitch | null;
|
||||
}
|
||||
|
||||
const trimNonEmpty = (value: string | undefined): string | null => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
};
|
||||
|
||||
const EarlyDesktopSettingsJson = fromLenientJson(
|
||||
Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
}),
|
||||
);
|
||||
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
|
||||
|
||||
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
|
||||
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
|
||||
|
||||
function resolveEarlyDesktopSettingsPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
}): string {
|
||||
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory: input.homeDirectory,
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment: isDevelopmentEnvironment(input.env),
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
return input.joinPath(stateDir, "desktop-settings.json");
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxPasswordStorePreference(
|
||||
input: EarlyDesktopSettingsInput,
|
||||
): LinuxPasswordStorePreference {
|
||||
const settingsPath = resolveEarlyDesktopSettingsPath(input);
|
||||
try {
|
||||
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
|
||||
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
|
||||
} catch {
|
||||
return DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxElectronOptions(
|
||||
input: EarlyLinuxElectronOptionsInput,
|
||||
): EarlyLinuxElectronOptions {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference(input);
|
||||
return {
|
||||
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
|
||||
passwordStore: resolveLinuxPasswordStoreSwitch({
|
||||
preference,
|
||||
env: input.env,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -65,6 +65,7 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.serverRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
assert.equal(environment.backendCwd, "/repo");
|
||||
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
|
||||
@@ -98,6 +99,24 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the packaged Windows server sidecar as the backend root", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment({
|
||||
platform: "win32",
|
||||
isPackaged: true,
|
||||
appPath: "/install/resources/app.asar",
|
||||
resourcesPath: "/install/resources",
|
||||
});
|
||||
|
||||
assert.equal(environment.appRoot, "/install/resources/app.asar");
|
||||
assert.equal(environment.serverRoot, "/install/resources/server.asar");
|
||||
assert.equal(
|
||||
environment.backendEntryPath,
|
||||
"/install/resources/server.asar/apps/server/dist/bin.mjs",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps implicit development state separate from production state", () =>
|
||||
Effect.gen(function* () {
|
||||
const development = yield* makeEnvironment(
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
export interface MakeDesktopEnvironmentInput {
|
||||
@@ -51,6 +52,13 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
// Root of the tree containing apps/server/dist and node_modules for the
|
||||
// backend. Equals appRoot everywhere except packaged Windows, where the
|
||||
// server tree ships as the resources/server.asar sidecar (see
|
||||
// scripts/build-desktop-artifact.ts) that the asar-aware
|
||||
// ELECTRON_RUN_AS_NODE primary reads in place and the WSL backend
|
||||
// extracts on demand (see DesktopWslServerTree).
|
||||
readonly serverRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
@@ -66,6 +74,8 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly linuxApplicationsDir: string;
|
||||
readonly appImagePath: Option.Option<string>;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
@@ -147,21 +157,34 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const serverRoot =
|
||||
input.isPackaged && input.platform === "win32"
|
||||
? path.join(input.resourcesPath, "server.asar")
|
||||
: appRoot;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
isDevelopment,
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
isDevelopment,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
|
||||
"applications",
|
||||
);
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
@@ -186,7 +209,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
|
||||
rootDir,
|
||||
appRoot,
|
||||
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
|
||||
serverRoot,
|
||||
backendEntryPath: path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
backendCwd: input.isPackaged ? homeDirectory : appRoot,
|
||||
preloadPath: path.join(input.dirname, "preload.cjs"),
|
||||
appUpdateYmlPath: input.isPackaged
|
||||
@@ -205,6 +229,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
linuxApplicationsDir,
|
||||
appImagePath: config.appImagePath,
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
|
||||
@@ -29,12 +29,13 @@ describe("DesktopLifecycle", () => {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -77,6 +78,7 @@ describe("DesktopLifecycle", () => {
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
zoomMain: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
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 PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
|
||||
interface RecordedRegistration {
|
||||
readonly directories: string[];
|
||||
readonly files: Array<{ readonly path: string; readonly content: string }>;
|
||||
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
|
||||
}
|
||||
|
||||
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "linux",
|
||||
isPackaged: true,
|
||||
isDevelopment: false,
|
||||
displayName: "T3 Code (Alpha)",
|
||||
linuxWmClass: "t3code",
|
||||
linuxApplicationsDir: "/home/alice/.local/share/applications",
|
||||
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
...overrides,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const mockProcess = (exitCode: number) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeHandlerLayer = (
|
||||
recorded: RecordedRegistration,
|
||||
input: {
|
||||
readonly environment?: Record<string, unknown>;
|
||||
readonly xdgMimeExitCode?: number;
|
||||
readonly writeError?: PlatformError.PlatformError;
|
||||
} = {},
|
||||
) =>
|
||||
DesktopLinuxUrlHandler.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
recorded.directories.push(path);
|
||||
}),
|
||||
writeFileString: (path, content) =>
|
||||
input.writeError
|
||||
? Effect.fail(input.writeError)
|
||||
: Effect.sync(() => {
|
||||
recorded.files.push({ path, content });
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
recorded.commands.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
});
|
||||
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runRegister = (
|
||||
recorded: RecordedRegistration,
|
||||
input: Parameters<typeof makeHandlerLayer>[1] = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
yield* handler.register;
|
||||
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
|
||||
|
||||
const emptyRecording = (): RecordedRegistration => ({
|
||||
directories: [],
|
||||
files: [],
|
||||
commands: [],
|
||||
});
|
||||
|
||||
describe("DesktopLinuxUrlHandler", () => {
|
||||
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
|
||||
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
|
||||
displayName: "T3 Code (Nightly)",
|
||||
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
|
||||
scheme: "t3code",
|
||||
});
|
||||
|
||||
assert.include(entry, "[Desktop Entry]");
|
||||
assert.include(entry, "Name=T3 Code (Nightly)");
|
||||
// Exec composes both escaping layers: a literal backslash becomes four
|
||||
// backslashes in the file, a quote three characters, a dollar sign two
|
||||
// backslashes plus the sign.
|
||||
assert.include(
|
||||
entry,
|
||||
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
|
||||
);
|
||||
assert.include(entry, "NoDisplay=true");
|
||||
assert.notInclude(entry, "StartupWMClass=");
|
||||
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
|
||||
});
|
||||
|
||||
it("carries structured context on registration errors", () => {
|
||||
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme: "t3code",
|
||||
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
cause: new Error("boom"),
|
||||
});
|
||||
assert.equal(
|
||||
writeError.message,
|
||||
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
|
||||
);
|
||||
assert.equal(
|
||||
writeError.desktopEntryPath,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
|
||||
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme: "t3code",
|
||||
exitCode: 4,
|
||||
});
|
||||
assert.equal(
|
||||
exitError.message,
|
||||
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded);
|
||||
|
||||
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
|
||||
assert.equal(recorded.files.length, 1);
|
||||
assert.equal(
|
||||
recorded.files[0]?.path,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
|
||||
);
|
||||
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
|
||||
assert.deepEqual(recorded.commands, [
|
||||
{
|
||||
command: "xdg-mime",
|
||||
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the process executable outside an AppImage", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
|
||||
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does nothing on other platforms or unpackaged builds", () => {
|
||||
const nonLinux = emptyRecording();
|
||||
const unpackaged = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
|
||||
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
|
||||
|
||||
for (const recorded of [nonLinux, unpackaged]) {
|
||||
assert.deepEqual(recorded.directories, []);
|
||||
assert.deepEqual(recorded.files, []);
|
||||
assert.deepEqual(recorded.commands, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("never fails startup when registration cannot complete", () => {
|
||||
const xdgMimeFailed = emptyRecording();
|
||||
const writeFailed = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
|
||||
yield* runRegister(writeFailed, {
|
||||
writeError: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFileString",
|
||||
description: "read-only filesystem",
|
||||
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(xdgMimeFailed.files.length, 1);
|
||||
assert.deepEqual(writeFailed.commands, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
// Linux ships as an AppImage, so the .desktop entry users end up with is
|
||||
// created by whatever integration tool they use (AppImageLauncher names it
|
||||
// appimagekit_<hash>-….desktop) and its filename is not under our control.
|
||||
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
|
||||
// setDesktopName, which cannot match those files — so the browser keeps
|
||||
// prompting "Choose an application" for every OAuth callback. Instead, write
|
||||
// our own handler entry pointing at the current AppImage and claim the
|
||||
// scheme default via xdg-mime, exactly what the file manager's "set as
|
||||
// default" checkbox would record in mimeapps.list.
|
||||
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
|
||||
|
||||
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
|
||||
|
||||
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
|
||||
"DesktopLinuxUrlHandlerRegistrationError",
|
||||
{
|
||||
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
|
||||
scheme: Schema.String,
|
||||
desktopEntryPath: Schema.optionalKey(Schema.String),
|
||||
exitCode: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
|
||||
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
|
||||
|
||||
const escapeDesktopEntryString = (value: string): string =>
|
||||
value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\n", "\\n")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\t", "\\t");
|
||||
|
||||
// Exec values are unescaped twice by implementations: first the general
|
||||
// string-value rules, then the Exec quoting rules — so writing composes the
|
||||
// layers in reverse. The argument is double-quoted with reserved characters
|
||||
// backslash-escaped and literal percent signs doubled (field codes), and the
|
||||
// general string escaping is applied on top: a literal backslash ends up as
|
||||
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
|
||||
export function escapeDesktopEntryExecArgument(value: string): string {
|
||||
const quoted = value
|
||||
.replaceAll("\\", () => "\\\\")
|
||||
.replaceAll("`", () => "\\`")
|
||||
.replaceAll("$", () => "\\$")
|
||||
.replaceAll('"', () => '\\"')
|
||||
.replaceAll("%", () => "%%");
|
||||
return escapeDesktopEntryString(`"${quoted}"`);
|
||||
}
|
||||
|
||||
// The AppImage integration entry owns the window identity and icon. This
|
||||
// hidden URL-only entry must not compete with it for StartupWMClass matching.
|
||||
export function renderUrlHandlerDesktopEntry(input: {
|
||||
readonly displayName: string;
|
||||
readonly execTarget: string;
|
||||
readonly scheme: string;
|
||||
}): string {
|
||||
return [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
`Name=${escapeDesktopEntryString(input.displayName)}`,
|
||||
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
|
||||
"Terminal=false",
|
||||
"NoDisplay=true",
|
||||
"StartupNotify=false",
|
||||
`MimeType=x-scheme-handler/${input.scheme};`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export class DesktopLinuxUrlHandler extends Context.Service<
|
||||
DesktopLinuxUrlHandler,
|
||||
{
|
||||
readonly register: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
|
||||
const desktopEntryPath = environment.path.join(
|
||||
environment.linuxApplicationsDir,
|
||||
URL_HANDLER_DESKTOP_ENTRY_NAME,
|
||||
);
|
||||
|
||||
const writeDesktopEntry = Effect.gen(function* () {
|
||||
// Inside the mounted AppImage, process.execPath points at a transient
|
||||
// /tmp/.mount_* path — the handler must launch the AppImage itself.
|
||||
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
|
||||
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
desktopEntryPath,
|
||||
renderUrlHandlerDesktopEntry({
|
||||
displayName: environment.displayName,
|
||||
execTarget,
|
||||
scheme,
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme,
|
||||
desktopEntryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setDefaultHandler = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"xdg-mime",
|
||||
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isRegistrationError(error)
|
||||
? error
|
||||
: new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const register = Effect.gen(function* () {
|
||||
if (environment.platform !== "linux" || !environment.isPackaged) {
|
||||
return;
|
||||
}
|
||||
yield* writeDesktopEntry;
|
||||
yield* setDefaultHandler;
|
||||
yield* logInfo("registered URL scheme handler", { scheme });
|
||||
}).pipe(
|
||||
// Registration is best-effort: a missing xdg-mime or read-only home must
|
||||
// never block startup — the OS chooser remains as fallback.
|
||||
Effect.catch((error) =>
|
||||
logWarning("URL scheme handler registration failed", {
|
||||
scheme,
|
||||
step: error.step,
|
||||
message: error.message,
|
||||
...(error.desktopEntryPath === undefined
|
||||
? {}
|
||||
: { desktopEntryPath: error.desktopEntryPath }),
|
||||
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.linuxUrlHandler.register"),
|
||||
);
|
||||
|
||||
return DesktopLinuxUrlHandler.of({ register });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
|
||||
@@ -49,20 +49,41 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopObservability", () => {
|
||||
it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const initial = DesktopObservability.appendBoundedOutputChunk(
|
||||
{
|
||||
runId: "test-run",
|
||||
startDetails: "pid=123",
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
},
|
||||
"stderr",
|
||||
new Uint8Array(maxBufferedBytes),
|
||||
);
|
||||
const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
|
||||
|
||||
const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
|
||||
|
||||
assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
|
||||
assert.equal(next.chunks[0]?.offset, 1);
|
||||
assert.equal(next.byteLength, maxBufferedBytes);
|
||||
});
|
||||
|
||||
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -112,26 +133,34 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
@@ -139,16 +168,18 @@ describe("DesktopObservability", () => {
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.instanceId, "primary");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.instanceId, "primary");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -157,6 +188,141 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.instanceId, "primary");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-snapshot-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
|
||||
yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
|
||||
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
);
|
||||
|
||||
const records = yield* Effect.forEach(
|
||||
(yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
|
||||
(line) => decodeDesktopBackendChildLogRecord(line),
|
||||
);
|
||||
assert.equal(
|
||||
records.some((record) => record.annotations.text === "after timeout\n"),
|
||||
true,
|
||||
);
|
||||
assert.equal(records.at(-1)?.annotations.details, "code=1");
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -24,7 +24,9 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -32,14 +34,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
@@ -127,10 +129,80 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
readonly offset: number;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
export function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) break;
|
||||
const retainedByteLength = first.chunk.byteLength - first.offset;
|
||||
if (retainedByteLength <= overflow) {
|
||||
overflow -= retainedByteLength;
|
||||
byteLength -= retainedByteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
offset: first.offset + overflow,
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
const chunk = chunks[index];
|
||||
byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
@@ -345,47 +417,93 @@ const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
Effect.gen(function* () {
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
|
||||
function* (session: BackendOutputSession, details: string) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
phase: "START",
|
||||
details: session.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk.subarray(output.offset)),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
);
|
||||
return {
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(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,
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailureSnapshot: Effect.fn(
|
||||
"desktop.observability.backendOutput.persistFailureSnapshot",
|
||||
)(function* ({ details }) {
|
||||
const session = yield* Ref.get(sessionRef);
|
||||
if (Option.isSome(session)) {
|
||||
yield* writeFailure(session.value, details);
|
||||
}
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
|
||||
function* ({ details }) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
|
||||
if (Option.isNone(session)) return;
|
||||
yield* writeFailure(session.value, details);
|
||||
},
|
||||
),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
} satisfies DesktopBackendOutputLogShape;
|
||||
}),
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
@@ -412,10 +530,9 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
return makeBackendOutputLogShape(environment, id, cached).pipe(
|
||||
Effect.map((outputLog) => [outputLog, cache] as const),
|
||||
);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
@@ -424,11 +541,19 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
return { sink, next };
|
||||
}),
|
||||
Effect.flatMap(({ sink, next }) =>
|
||||
makeBackendOutputLogShape(environment, id, sink).pipe(
|
||||
Effect.map(
|
||||
(outputLog) =>
|
||||
[
|
||||
outputLog,
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
|
||||
() => ({
|
||||
appendSwitchMock: vi.fn(),
|
||||
getSwitchValueMock: vi.fn(),
|
||||
hasSwitchMock: vi.fn(),
|
||||
registerSchemesMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
getSwitchValue: getSwitchValueMock,
|
||||
hasSwitch: hasSwitchMock,
|
||||
},
|
||||
},
|
||||
protocol: {
|
||||
registerSchemesAsPrivileged: registerSchemesMock,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
|
||||
describe("DesktopPreReadyPlatform", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockReset();
|
||||
getSwitchValueMock.mockReset();
|
||||
hasSwitchMock.mockReset();
|
||||
registerSchemesMock.mockReset();
|
||||
});
|
||||
|
||||
it("reads an explicit Electron command-line switch value", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: (switchName) => switchName === "password-store",
|
||||
getSwitchValue: (switchName) => {
|
||||
assert.equal(switchName, "password-store");
|
||||
return "basic";
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.equal(value, "basic");
|
||||
});
|
||||
|
||||
it("treats valueless Electron command-line switches as absent", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => true,
|
||||
getSwitchValue: () => "",
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it("returns null for missing Electron command-line switches", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => false,
|
||||
getSwitchValue: () => {
|
||||
throw new Error("Unexpected switch value read.");
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
|
||||
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
|
||||
) {}
|
||||
|
||||
const events: Array<string> = [];
|
||||
registerSchemesMock.mockImplementation(() => {
|
||||
events.push("pre-ready");
|
||||
});
|
||||
|
||||
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
|
||||
);
|
||||
|
||||
const clerkShapedLayer = Layer.effect(
|
||||
ClerkShaped,
|
||||
Effect.promise(() => Promise.resolve()).pipe(
|
||||
Effect.map(() => {
|
||||
events.push("clerk");
|
||||
return { ready: true as const };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runtimeLayer = clerkShapedLayer.pipe(
|
||||
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(preReadyLayer),
|
||||
);
|
||||
|
||||
const result = yield* Effect.all({
|
||||
clerk: ClerkShaped,
|
||||
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
assert.deepEqual(result, {
|
||||
clerk: { ready: true },
|
||||
preReady: {
|
||||
linux: null,
|
||||
linuxPasswordStoreCommandLine: null,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, ["pre-ready", "clerk"]);
|
||||
assert.equal(registerSchemesMock.mock.calls.length, 1);
|
||||
assert.equal(appendSwitchMock.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
|
||||
export interface DesktopPreReadyCommandLineReader {
|
||||
readonly hasSwitch: (switchName: string) => boolean;
|
||||
readonly getSwitchValue: (switchName: string) => string;
|
||||
}
|
||||
|
||||
export function readCommandLineSwitchValue(
|
||||
commandLine: DesktopPreReadyCommandLineReader,
|
||||
switchName: string,
|
||||
): string | null {
|
||||
if (!commandLine.hasSwitch(switchName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = commandLine.getSwitchValue(switchName).trim();
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export const resolveEarlyLinuxElectronOptionsFromProcess =
|
||||
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
|
||||
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
|
||||
env: process.env,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
joinPath: NodePath.posix.join,
|
||||
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
|
||||
});
|
||||
|
||||
export class DesktopPreReadyElectronOptions extends Context.Service<
|
||||
DesktopPreReadyElectronOptions,
|
||||
{
|
||||
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
|
||||
readonly linuxPasswordStoreCommandLine: string | null;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
|
||||
const linuxPasswordStoreCommandLine =
|
||||
platform === "linux"
|
||||
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
|
||||
: null;
|
||||
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
|
||||
|
||||
if (linux !== null) {
|
||||
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
|
||||
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
|
||||
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
|
||||
}
|
||||
}
|
||||
|
||||
return { linux, linuxPasswordStoreCommandLine };
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
|
||||
|
||||
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
|
||||
// observe app readiness before scheme privileges and command-line switches exist.
|
||||
export const layer = Layer.mergeAll(
|
||||
ElectronProtocol.layerSchemePrivileges,
|
||||
Layer.effect(DesktopPreReadyElectronOptions, make),
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
export type JoinPath = (first: string, ...segments: string[]) => string;
|
||||
|
||||
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
|
||||
if (Option.isNone(t3Home)) {
|
||||
return Option.none();
|
||||
}
|
||||
const trimmed = t3Home.value.trim();
|
||||
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
|
||||
}
|
||||
|
||||
export function resolveDesktopBaseDir(input: {
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
|
||||
input.joinPath(input.homeDirectory, ".t3"),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveDesktopStateDir(input: {
|
||||
readonly baseDir: string;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
const useDevSubdir =
|
||||
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
|
||||
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
|
||||
}
|
||||
@@ -17,6 +17,7 @@ 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";
|
||||
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -52,6 +53,7 @@ function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly dirname?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
@@ -59,7 +61,7 @@ function makeEnvironmentLayer(
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
dirname: options?.dirname ?? "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: options?.platform ?? "darwin",
|
||||
processArch: "x64",
|
||||
@@ -114,6 +116,7 @@ const withHarness = <A, E, R>(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -152,6 +155,47 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolvePrimary;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
DesktopWslServerTree.DesktopWslServerTree,
|
||||
DesktopWslServerTree.DesktopWslServerTree.of({
|
||||
ensure: Effect.die("Windows primary must not extract the WSL server tree"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: `${resourcesPath}/app.asar`,
|
||||
platform: "win32",
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);
|
||||
assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
@@ -172,7 +216,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
@@ -185,6 +229,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -233,7 +278,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
@@ -249,6 +294,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -385,6 +431,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
@@ -426,6 +473,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
@@ -464,6 +512,8 @@ describe("DesktopBackendConfiguration", () => {
|
||||
// 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);
|
||||
assert.notProperty(config.bootstrap, "desktopTelemetryFd");
|
||||
assert.notProperty(config.bootstrap, "resourceMonitorPath");
|
||||
// httpBaseUrl uses the resolved distro IP from the test stub,
|
||||
// not localhost — the renderer reaches the backend directly to
|
||||
// avoid relying on wslhost forwarding.
|
||||
@@ -483,6 +533,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -533,6 +584,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslOnly: true,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -570,6 +622,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Removed-Distro",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -603,6 +656,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -637,6 +691,49 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.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 surfaces sidecar extraction failures through typed preflight", () =>
|
||||
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, "could not be extracted");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslServerTree.layerTest({
|
||||
result: {
|
||||
ok: false,
|
||||
reason: "WSL server files could not be extracted",
|
||||
fatal: false,
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -669,6 +766,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -705,6 +803,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -713,6 +812,99 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
|
||||
const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(
|
||||
`${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
|
||||
{ recursive: true },
|
||||
);
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: `${resourcesPath}/app.asar`,
|
||||
dirname,
|
||||
isPackaged: true,
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("prefers the release resource monitor when both development builds exist", () =>
|
||||
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 dirname = path.join(baseDir, "apps/desktop/src");
|
||||
const releaseMonitorPath = path.join(
|
||||
baseDir,
|
||||
"native/resource-monitor/target/release/t3-resource-monitor",
|
||||
);
|
||||
const debugMonitorPath = path.join(
|
||||
baseDir,
|
||||
"native/resource-monitor/target/debug/t3-resource-monitor",
|
||||
);
|
||||
yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
|
||||
yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(releaseMonitorPath, "release");
|
||||
yield* fileSystem.writeFileString(debugMonitorPath, "debug");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
dirname,
|
||||
devServerUrl: "http://127.0.0.1:5733",
|
||||
isPackaged: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
@@ -749,6 +941,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -770,6 +963,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.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.
|
||||
|
||||
@@ -19,6 +19,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
|
||||
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
@@ -141,6 +142,44 @@ const logBackendObservabilitySettingsReadFailure = (
|
||||
);
|
||||
};
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.isPackaged
|
||||
? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -326,7 +365,9 @@ const buildObservabilityFragment = (observabilitySettings: BackendObservabilityS
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
input: SharedBootstrapInput & {
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -345,6 +386,12 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
@@ -378,10 +425,12 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| DesktopWslServerTree.DesktopWslServerTree
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
|
||||
// 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
|
||||
@@ -411,34 +460,38 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
// The packaged sidecar is a Windows executable and cannot run inside the
|
||||
// Linux WSL backend. Keep the field absent instead of passing an unusable
|
||||
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
|
||||
// See docs/architecture/resource-telemetry.md.
|
||||
...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;
|
||||
// In packaged builds the server tree ships inside resources/server.asar —
|
||||
// an archive FILE the Windows primary reads through ELECTRON_RUN_AS_NODE
|
||||
// (asar-aware). The WSL backend launches plain `wsl.exe -- node`, which
|
||||
// can't read an asar, so materialize (or reuse) the extracted copy of the
|
||||
// sidecar before preflighting. In dev the server tree is the real checkout
|
||||
// directory and ensure returns it unchanged.
|
||||
const serverTree = yield* wslServerTree.ensure;
|
||||
const wslAppRoot = serverTree.ok ? serverTree.root : environment.serverRoot;
|
||||
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,
|
||||
});
|
||||
const preflight = serverTree.ok
|
||||
? 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,
|
||||
})
|
||||
: ({ _tag: "Failed", reason: serverTree.reason, fatal: serverTree.fatal } as const);
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
@@ -560,6 +613,7 @@ export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
@@ -615,13 +669,18 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
@@ -673,6 +732,7 @@ export const make = Effect.gen(function* () {
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -21,10 +24,15 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -41,6 +49,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
bootstrapDelivery: "fd3",
|
||||
extendEnv: true,
|
||||
@@ -52,14 +62,16 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
...baseConfig.bootstrap,
|
||||
tailscaleServeEnabled: true,
|
||||
desktopTelemetryFd: 4,
|
||||
otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
|
||||
};
|
||||
|
||||
function makeProcess(options?: {
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -71,7 +83,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -112,7 +124,14 @@ interface MakeInstanceInput {
|
||||
failure: DesktopBackendManager.PreflightFailure,
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
readonly configResolve?: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
}
|
||||
|
||||
// Helper that constructs a primary backend instance using the factory
|
||||
@@ -122,8 +141,11 @@ interface MakeInstanceInput {
|
||||
// to drive the instance's lifecycle.
|
||||
function makeTestInstance(input: MakeInstanceInput) {
|
||||
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
};
|
||||
const servicesLayer = Layer.mergeAll(
|
||||
@@ -135,6 +157,16 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () => Effect.succeed(stubLog),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: input.desktopTelemetryStream ?? Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
|
||||
const instance = DesktopBackendManager.makeBackendInstance({
|
||||
@@ -150,11 +182,12 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
let bootstrapJson = "";
|
||||
let telemetryJson = "";
|
||||
let readyCount = 0;
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
@@ -169,6 +202,10 @@ describe("DesktopBackendManager", () => {
|
||||
if (fd3?.type === "input" && fd3.stream) {
|
||||
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
}
|
||||
const fd4 = command.options.additionalFds?.fd4;
|
||||
if (fd4?.type === "input" && fd4.stream) {
|
||||
telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
}
|
||||
}
|
||||
|
||||
return makeProcess({
|
||||
@@ -184,12 +221,14 @@ describe("DesktopBackendManager", () => {
|
||||
bootstrap: configWithObservability,
|
||||
},
|
||||
spawnerLayer,
|
||||
desktopTelemetryStream: Stream.encodeText(
|
||||
Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
|
||||
),
|
||||
onReady: Effect.sync(() => {
|
||||
readyCount += 1;
|
||||
}).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,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -210,16 +249,400 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
|
||||
assert.equal(
|
||||
telemetryJson,
|
||||
'{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves the readiness timeout cause and process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
httpClientLayer((request) =>
|
||||
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const readiness = yield* DesktopBackendManager.waitForHttpReady({
|
||||
executablePath: baseConfig.executablePath,
|
||||
entryPath: baseConfig.entryPath,
|
||||
cwd: baseConfig.cwd,
|
||||
httpBaseUrl: baseConfig.httpBaseUrl,
|
||||
timeout: Duration.millis(50),
|
||||
}).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
const request = yield* Deferred.await(requested);
|
||||
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(readiness);
|
||||
|
||||
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
assert.equal(error.timeoutMs, 50);
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports bootstrap encoding failures with stable process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessBootstrapEncodeError") {
|
||||
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
|
||||
);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves spawn failures without deriving their message from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcessSpawner",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: baseConfig.executablePath,
|
||||
description: "low-level detail that must not become the public message",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessSpawnError") {
|
||||
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, spawnCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
|
||||
);
|
||||
assert.notInclude(error.message, spawnCause.message);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves exit-status failures without copying their detail into the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const exitCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "exit-status-secret-sentinel",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Effect.fail(exitCause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessExitStatusError") {
|
||||
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, exitCause);
|
||||
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
|
||||
assert.notInclude(error.message, "exit-status-secret-sentinel");
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output stream failures with process and stream context", () =>
|
||||
Effect.gen(function* () {
|
||||
const outputCause = PlatformError.systemError({
|
||||
_tag: "BadResource",
|
||||
module: "ChildProcess",
|
||||
method: "stdout",
|
||||
description: "output-stream-secret-sentinel",
|
||||
});
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fail(outputCause),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputReadError") {
|
||||
return assert.fail(`Expected output read error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
|
||||
assert.notInclude(error.message, "output-stream-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output handler failures separately from stream read failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const chunk = new TextEncoder().encode("backend output");
|
||||
const nextChunk = new TextEncoder().encode("still draining");
|
||||
const outputCause = new Error("output-handler-secret-sentinel");
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const drained = yield* Deferred.make<void>();
|
||||
let outputCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.make(chunk, nextChunk),
|
||||
exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutput: () => {
|
||||
outputCount += 1;
|
||||
return outputCount === 1
|
||||
? Effect.fail(outputCause)
|
||||
: Deferred.succeed(drained, void 0).pipe(Effect.asVoid);
|
||||
},
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputHandlingError") {
|
||||
return assert.fail(`Expected output handling error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.equal(error.chunkByteLength, chunk.byteLength);
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
|
||||
);
|
||||
assert.notInclude(error.message, "output-handler-secret-sentinel");
|
||||
assert.equal(outputCount, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports child exit before waiting for trailing output to drain", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const exitObserved = yield* Deferred.make<void>();
|
||||
const finishOutputDrain = yield* Deferred.make<void>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.await(finishOutputDrain).pipe(
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runFiber = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
|
||||
}).pipe(
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* Deferred.await(exitObserved);
|
||||
assert.isUndefined(runFiber.pollUnsafe());
|
||||
|
||||
yield* Deferred.succeed(finishOutputDrain, void 0);
|
||||
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5
|
||||
? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
|
||||
: Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
message.type === "setDiagnosticsDemand"
|
||||
? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
|
||||
const outputDrainStarted = yield* Deferred.make<void>();
|
||||
const outputChunks = yield* Ref.make<Array<string>>([]);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.succeed(outputDrainStarted, void 0).pipe(
|
||||
Effect.andThen(Effect.sleep(Duration.seconds(1))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
writeOutputChunk: (_streamName, chunk) =>
|
||||
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
|
||||
persistFailure: () =>
|
||||
Ref.get(outputChunks).pipe(
|
||||
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -256,8 +679,7 @@ describe("DesktopBackendManager", () => {
|
||||
readyCount += 1;
|
||||
}).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,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -285,9 +707,15 @@ describe("DesktopBackendManager", () => {
|
||||
let startCount = 0;
|
||||
let closedCount = 0;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
const startedPids = yield* Queue.unbounded<number>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReadyFlag = yield* Ref.make(false);
|
||||
let shutdownCount = 0;
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
let removedTelemetrySources = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -296,9 +724,16 @@ describe("DesktopBackendManager", () => {
|
||||
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 close = Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Deferred.succeed(closed, void 0)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
|
||||
@@ -316,7 +751,28 @@ describe("DesktopBackendManager", () => {
|
||||
Effect.andThen(Deferred.succeed(ready, void 0)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
onShutdown: Ref.set(backendReadyFlag, false),
|
||||
onShutdown: Ref.set(backendReadyFlag, false).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
shutdownCount += 1;
|
||||
}),
|
||||
),
|
||||
),
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
desktopTelemetryPublisher: {
|
||||
removeControlSource: () =>
|
||||
Effect.sync(() => {
|
||||
removedTelemetrySources += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
assert.isTrue(Option.isNone(yield* instance.currentConfig));
|
||||
|
||||
@@ -330,12 +786,21 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(runningSnapshot.ready, true);
|
||||
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
|
||||
|
||||
yield* instance.stop();
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
assert.isFalse(yield* Ref.get(backendReadyFlag));
|
||||
assert.equal(shutdownCount, 1);
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
assert.equal(removedTelemetrySources, 1);
|
||||
|
||||
const stoppedSnapshot = yield* instance.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReadyFlag));
|
||||
assert.equal(shutdownCount, 1);
|
||||
assert.equal(stoppedSnapshot.desiredRunning, false);
|
||||
assert.equal(stoppedSnapshot.ready, false);
|
||||
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
|
||||
@@ -343,6 +808,213 @@ describe("DesktopBackendManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("restarts when start is requested during stop teardown", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
assert.equal((yield* instance.snapshot).desiredRunning, true);
|
||||
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
const restarted = yield* instance.snapshot;
|
||||
assert.equal(restarted.desiredRunning, true);
|
||||
assert.deepEqual(restarted.activePid, Option.some(123));
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries config resolution after a start request during stop teardown", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
const configAttempts = yield* Ref.make(0);
|
||||
let startCount = 0;
|
||||
|
||||
const configFailure = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "DesktopBackendManager",
|
||||
method: "configResolve",
|
||||
description: "transient configuration failure",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
|
||||
Effect.flatMap((attempt) =>
|
||||
attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
configResolve,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
|
||||
const pendingRestart = yield* instance.snapshot;
|
||||
assert.equal(pendingRestart.desiredRunning, true);
|
||||
assert.equal(pendingRestart.restartScheduled, true);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
assert.equal(yield* Ref.get(configAttempts), 3);
|
||||
assert.equal((yield* instance.snapshot).desiredRunning, true);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps a timed-out run active until its process exits", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance
|
||||
.stop({ timeout: Duration.millis(100) })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
|
||||
assert.equal(startCount, 1);
|
||||
const timedOut = yield* instance.snapshot;
|
||||
assert.equal(timedOut.desiredRunning, true);
|
||||
assert.deepEqual(timedOut.activePid, Option.some(123));
|
||||
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not notify shutdown before the first start has prior state", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -383,6 +1055,7 @@ describe("DesktopBackendManager", () => {
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -402,11 +1075,15 @@ describe("DesktopBackendManager", () => {
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(499));
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
@@ -657,6 +1334,13 @@ describe("DesktopBackendManager", () => {
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* instance.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -33,7 +33,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -46,10 +45,13 @@ import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
@@ -62,7 +64,10 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
|
||||
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
const { logWarning: logBackendProcessWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-process");
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
|
||||
@@ -70,13 +75,17 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly args: ReadonlyArray<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
|
||||
@@ -106,55 +115,122 @@ export interface PreflightFailure {
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
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}.`;
|
||||
}
|
||||
}
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
{
|
||||
entryPath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
executablePath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly outputDrainTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onExitObserved?: () => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -225,6 +301,8 @@ interface ActiveBackendRun {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
|
||||
readonly pid: Option.Option<number>;
|
||||
readonly exitObserved: boolean;
|
||||
readonly stopRequested: boolean;
|
||||
}
|
||||
|
||||
interface BackendManagerState {
|
||||
@@ -266,76 +344,130 @@ const calculateRestartDelay = (attempt: number): Duration.Duration =>
|
||||
|
||||
const closeRun = (
|
||||
run: ActiveBackendRun,
|
||||
parentScope: Scope.Scope,
|
||||
options?: { readonly timeout?: Duration.Duration },
|
||||
): Effect.Effect<void> => {
|
||||
): Effect.Effect<boolean> => {
|
||||
const waitForFiber = Option.match(run.fiber, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
|
||||
});
|
||||
const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
|
||||
const timeout = options?.timeout;
|
||||
|
||||
return (
|
||||
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
|
||||
).pipe(Effect.ignore);
|
||||
if (!timeout) {
|
||||
return close.pipe(Effect.as(true));
|
||||
}
|
||||
|
||||
return Effect.forkIn(close, parentScope).pipe(
|
||||
Effect.flatMap((closeFiber) =>
|
||||
Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
export const waitForHttpReady = (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
baseUrl: options.httpBaseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
makeError: ({ cause }) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
|
||||
if (options.bootstrapDelivery === "fd3") {
|
||||
additionalFds.fd3 = {
|
||||
type: "input",
|
||||
stream: bootstrapStream,
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
}
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
@@ -350,34 +482,131 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
// 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 } } }
|
||||
: {}),
|
||||
...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
|
||||
});
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.splitLines,
|
||||
Stream.filter((line) => line.trim().length > 0),
|
||||
Stream.runForEach((line) =>
|
||||
decodeDesktopTelemetryControlLine(line).pipe(
|
||||
Effect.flatMap(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendProcessWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
outputFibers.push(
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
);
|
||||
}
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
const exit = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
yield* options.onExitObserved?.() ?? Effect.void;
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(
|
||||
Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
|
||||
Effect.ignore,
|
||||
);
|
||||
if (Exit.isFailure(exit)) {
|
||||
return yield* Effect.failCause(exit.cause);
|
||||
}
|
||||
const exitCode = exit.value;
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
});
|
||||
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
@@ -394,12 +623,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| DesktopTelemetryPublisher.DesktopTelemetryPublisher
|
||||
| Scope.Scope
|
||||
> {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
@@ -444,6 +675,12 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isSome(current.active)) {
|
||||
if (!current.desiredRunning) {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -462,6 +699,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
Effect.option,
|
||||
);
|
||||
if (Option.isNone(config)) {
|
||||
if (current.desiredRunning) {
|
||||
yield* scheduleRestart("failed to generate desktop backend configuration");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const entryExists = yield* fileSystem
|
||||
@@ -561,6 +801,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
scope: runScope,
|
||||
fiber: Option.none(),
|
||||
pid: Option.none(),
|
||||
exitObserved: false,
|
||||
stopRequested: false,
|
||||
} satisfies ActiveBackendRun),
|
||||
nextRunId: latest.nextRunId + 1,
|
||||
},
|
||||
@@ -571,54 +813,70 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const { isCurrentRun, nextState, pid } = yield* Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly isCurrentRun: boolean;
|
||||
readonly nextState: BackendManagerState;
|
||||
readonly pid: Option.Option<number>;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const currentRun = Option.getOrUndefined(latest.active);
|
||||
if (currentRun?.id !== runId) {
|
||||
const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
|
||||
yield* Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly isCurrentRun: boolean;
|
||||
readonly nextState: BackendManagerState;
|
||||
readonly pid: Option.Option<number>;
|
||||
readonly exitObserved: boolean;
|
||||
readonly stopRequested: boolean;
|
||||
readonly wasReady: boolean;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const currentRun = Option.getOrUndefined(latest.active);
|
||||
if (currentRun?.id !== runId) {
|
||||
return [
|
||||
{
|
||||
isCurrentRun: false,
|
||||
nextState: latest,
|
||||
pid: Option.none<number>(),
|
||||
exitObserved: false,
|
||||
stopRequested: false,
|
||||
wasReady: false,
|
||||
},
|
||||
latest,
|
||||
] as const;
|
||||
}
|
||||
|
||||
const next = {
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
ready: false,
|
||||
};
|
||||
return [
|
||||
{
|
||||
isCurrentRun: false,
|
||||
nextState: latest,
|
||||
pid: Option.none<number>(),
|
||||
isCurrentRun: true,
|
||||
nextState: next,
|
||||
pid: currentRun.pid,
|
||||
exitObserved: currentRun.exitObserved,
|
||||
stopRequested: currentRun.stopRequested,
|
||||
wasReady: latest.ready,
|
||||
},
|
||||
latest,
|
||||
next,
|
||||
] as const;
|
||||
}
|
||||
|
||||
const next = {
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
ready: false,
|
||||
};
|
||||
return [
|
||||
{
|
||||
isCurrentRun: true,
|
||||
nextState: next,
|
||||
pid: currentRun.pid,
|
||||
},
|
||||
next,
|
||||
] as const;
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (isCurrentRun) {
|
||||
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
|
||||
if (Option.isSome(pid)) {
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
if (exitObserved && !stopRequested) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
}
|
||||
if (wasReady) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -630,16 +888,23 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: (message) =>
|
||||
desktopTelemetryPublisher.handleControlForSource(spec.id, message),
|
||||
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
}));
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
yield* backendOutputLog.beginSession({
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onExitObserved: () =>
|
||||
updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
exitObserved: true,
|
||||
})),
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
@@ -662,10 +927,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
});
|
||||
yield* backendOutputLog.persistFailureSnapshot({
|
||||
details: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -750,41 +1021,92 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Ref.modify(state, (latest) => [
|
||||
{
|
||||
active: latest.active,
|
||||
restartFiber: latest.restartFiber,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
// 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);
|
||||
const result = yield* Ref.modify(state, (latest) => {
|
||||
const active = Option.map(latest.active, (run) =>
|
||||
run.exitObserved ? run : { ...run, stopRequested: true },
|
||||
);
|
||||
return [
|
||||
{
|
||||
active,
|
||||
restartFiber: latest.restartFiber,
|
||||
notifyShutdown: latest.ready,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
active,
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
|
||||
if (notifyShutdown) {
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
}
|
||||
yield* Option.match(restartFiber, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options),
|
||||
onSome: (run) =>
|
||||
Effect.gen(function* () {
|
||||
const closed = yield* closeRun(run, parentScope, options);
|
||||
if (!closed) {
|
||||
return;
|
||||
}
|
||||
const cleanup = yield* mutex.withPermits(1)(
|
||||
Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly needsCleanup: boolean;
|
||||
readonly shouldStart: boolean;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const current = Option.getOrUndefined(latest.active);
|
||||
if (current?.id !== run.id) {
|
||||
return [
|
||||
{
|
||||
needsCleanup: false,
|
||||
shouldStart:
|
||||
latest.desiredRunning &&
|
||||
Option.isNone(latest.active) &&
|
||||
Option.isNone(latest.restartFiber),
|
||||
},
|
||||
latest,
|
||||
];
|
||||
}
|
||||
return [
|
||||
{
|
||||
needsCleanup: true,
|
||||
shouldStart: latest.desiredRunning,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
},
|
||||
];
|
||||
},
|
||||
),
|
||||
);
|
||||
if (cleanup.needsCleanup) {
|
||||
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
if (cleanup.shouldStart) {
|
||||
yield* start;
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,11 +5,13 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
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 DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
@@ -56,10 +58,21 @@ function makePoolLayer(
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
@@ -78,6 +91,7 @@ function makePoolLayer(
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.die("unexpected menu action"),
|
||||
zoomMain: () => Effect.die("unexpected zoom"),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]),
|
||||
),
|
||||
|
||||
@@ -97,6 +97,7 @@ 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 DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
@@ -176,7 +177,8 @@ export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
|
||||
@@ -14,7 +14,7 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
requestSingleInstanceLockMock,
|
||||
removeSwitchMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -35,7 +35,7 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
requestSingleInstanceLockMock: vi.fn(() => true),
|
||||
removeSwitchMock: vi.fn(),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -54,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
removeSwitch: removeSwitchMock,
|
||||
},
|
||||
dock: {
|
||||
setIcon: setDockIconMock,
|
||||
@@ -67,7 +68,6 @@ vi.mock("electron", () => ({
|
||||
quit: quitMock,
|
||||
relaunch: relaunchMock,
|
||||
removeListener: removeListenerMock,
|
||||
requestSingleInstanceLock: requestSingleInstanceLockMock,
|
||||
runningUnderARM64Translation: false,
|
||||
setAboutPanelOptions: setAboutPanelOptionsMock,
|
||||
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
|
||||
@@ -92,6 +92,7 @@ describe("ElectronApp", () => {
|
||||
quitMock.mockClear();
|
||||
relaunchMock.mockClear();
|
||||
removeListenerMock.mockClear();
|
||||
removeSwitchMock.mockClear();
|
||||
setPathMock.mockClear();
|
||||
});
|
||||
|
||||
@@ -181,4 +182,13 @@ describe("ElectronApp", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("removes command-line switches through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
|
||||
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
});
|
||||
@@ -56,7 +56,7 @@ export class ElectronApp extends Context.Service<
|
||||
options: Electron.AboutPanelOptionsOptions,
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -69,6 +69,7 @@ export class ElectronApp extends Context.Service<
|
||||
readonly onBeforeQuitForUpdate: (
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
@@ -152,7 +153,7 @@ export const make = ElectronApp.of({
|
||||
Effect.sync(() => {
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
@@ -191,6 +192,10 @@ export const make = ElectronApp.of({
|
||||
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
removeCommandLineSwitch: (switchName) =>
|
||||
Effect.sync(() => {
|
||||
Electron.app.commandLine.removeSwitch(switchName);
|
||||
}),
|
||||
on: addScopedAppListener,
|
||||
});
|
||||
|
||||
|
||||
@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {
|
||||
showErrorBoxMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("returns false without opening a confirm dialog for empty messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: " ",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.equal(showMessageBoxMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens a confirm dialog for the owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
const owner = { id: 1 } as BrowserWindow;
|
||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.some(owner),
|
||||
});
|
||||
|
||||
assert.isTrue(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
owner,
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {
|
||||
}).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");
|
||||
|
||||
@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
@@ -23,17 +21,18 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
|
||||
"ElectronDialogPickFilesError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
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.`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +68,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
@@ -81,9 +80,10 @@ export interface ElectronDialogPickFolderInput {
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
export interface ElectronDialogPickFilesInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<
|
||||
@@ -92,9 +92,9 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
@@ -137,38 +137,31 @@ export const make = ElectronDialog.of({
|
||||
}
|
||||
return Option.fromNullishOr(result.filePaths[0]);
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = {
|
||||
properties: ["openFile", "multiSelections"],
|
||||
filters: [...input.filters],
|
||||
...(defaultPath === null ? {} : { defaultPath }),
|
||||
};
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
new ElectronDialogPickFilesError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
{
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitor["Service"]["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitor["Service"]["onThermalStateChange"] = (
|
||||
listener,
|
||||
) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
|
||||
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",
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
|
||||
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
@@ -104,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Must run synchronously during process bootstrap, before Electron emits `ready`.
|
||||
*/
|
||||
export function registerDesktopSchemePrivilegesSync(): void {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_PRODUCTION_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
scheme: DESKTOP_DEVELOPMENT_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
|
||||
);
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
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";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
|
||||
return ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
}),
|
||||
selectedStorageBackend: Effect.sync(() => {
|
||||
if (platform !== "linux") {
|
||||
return Option.none();
|
||||
}
|
||||
try {
|
||||
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
|
||||
} catch {
|
||||
return Option.none();
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronSafeStorage, make);
|
||||
export const layer = Layer.effect(ElectronSafeStorage, make);
|
||||
@@ -31,13 +31,13 @@ import {
|
||||
setUpdateChannel,
|
||||
} from "./methods/updates.ts";
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
pickThemeFiles,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
@@ -79,7 +79,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
|
||||
@@ -3,10 +3,15 @@ import {
|
||||
DesktopAppBrandingSchema,
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickedThemeFileSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type PickedThemeFile,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -215,19 +220,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
return yield* electronWindow.focusedMainOrFirst.pipe(
|
||||
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
@@ -268,3 +260,49 @@ export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
return yield* shell.openExternal(url);
|
||||
}),
|
||||
});
|
||||
|
||||
/** Theme files are a few KB; anything larger returns empty text and lets the
|
||||
* renderer reject it by size without the contents ever crossing the bridge. */
|
||||
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
|
||||
|
||||
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
|
||||
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
// The VS Code extensions directory is the same dotfolder on Windows,
|
||||
// macOS, and Linux; when it is missing the picker opens wherever the
|
||||
// platform would by default.
|
||||
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
|
||||
const defaultPath = yield* fileSystem
|
||||
.exists(extensionsDir)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const paths = yield* dialog.pickFiles({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
|
||||
filters: [{ name: "JSON", extensions: ["json"] }],
|
||||
});
|
||||
if (paths.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.forEach(paths, (filePath) => {
|
||||
const name = path.basename(filePath);
|
||||
return Effect.gen(function* () {
|
||||
const info = yield* fileSystem.stat(filePath);
|
||||
const size = Number(info.size);
|
||||
if (size > PICKED_THEME_FILE_MAX_BYTES) {
|
||||
return { name, size, text: "" } satisfies PickedThemeFile;
|
||||
}
|
||||
const text = yield* fileSystem.readFileString(filePath);
|
||||
return { name, size, text } satisfies PickedThemeFile;
|
||||
}).pipe(
|
||||
// An unreadable file degrades to an entry the renderer reports.
|
||||
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
|
||||
);
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
resolveLinuxSecretStorageUnavailableMessage,
|
||||
} from "./linuxSecretStorage.ts";
|
||||
|
||||
const autoSwitch = (env: NodeJS.ProcessEnv) =>
|
||||
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
|
||||
|
||||
describe("linuxSecretStorage", () => {
|
||||
it("preserves explicit supported password-store preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
|
||||
});
|
||||
|
||||
it("falls back to auto for missing or unsupported preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
|
||||
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
|
||||
});
|
||||
|
||||
it("uses explicit preferences instead of the auto heuristic", () => {
|
||||
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
|
||||
).toBe(preference);
|
||||
// An explicit preference also wins where auto would have stayed out of the way.
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
|
||||
).toBe(preference);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not force a password-store for desktops Electron already recognizes", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
|
||||
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({})).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
|
||||
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
|
||||
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("overrides KDE sessions identified only by legacy variables", () => {
|
||||
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
|
||||
// basic text for the rest. Either way these are the variables a previous session leaves behind,
|
||||
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
|
||||
for (const session of [
|
||||
"kde",
|
||||
"kde-plasma",
|
||||
"kde4",
|
||||
"plasma",
|
||||
"plasmawayland",
|
||||
"plasmawayland-dev",
|
||||
"plasmax11",
|
||||
"plasmax11-dev",
|
||||
]) {
|
||||
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
|
||||
}
|
||||
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
|
||||
expect(
|
||||
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
|
||||
).toBe("gnome-libsecret");
|
||||
// A previous KDE session left these behind; the compositor running now is not KDE.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
|
||||
expect(
|
||||
autoSwitch({
|
||||
XDG_CURRENT_DESKTOP: "Hyprland",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
KDE_SESSION_VERSION: "6",
|
||||
}),
|
||||
).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "gnome-libsecret",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet6",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet",
|
||||
selectedBackend: "gnome-libsecret",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
});
|
||||
|
||||
it("uses KWallet remediation wording for KDE-looking sessions", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "kwallet6",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { DESKTOP_SESSION: "plasmawayland" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
// A desktop name outranks a bare KDE marker when choosing the wording.
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
export type LinuxPasswordStorePreference =
|
||||
| "auto"
|
||||
| "gnome-libsecret"
|
||||
| "kwallet"
|
||||
| "kwallet5"
|
||||
| "kwallet6";
|
||||
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
|
||||
|
||||
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
|
||||
|
||||
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
|
||||
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
|
||||
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
|
||||
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
|
||||
"Deepin",
|
||||
"GNOME",
|
||||
"Pantheon",
|
||||
"UKUI",
|
||||
"Unity",
|
||||
"X-Cinnamon",
|
||||
"XFCE",
|
||||
]);
|
||||
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
|
||||
const ELECTRON_KDE_DESKTOP = "KDE";
|
||||
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
|
||||
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
|
||||
|
||||
const KDE_NAME_PREFIXES = ["kde", "plasma"];
|
||||
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
export function normalizeLinuxPasswordStorePreference(
|
||||
value: unknown,
|
||||
): LinuxPasswordStorePreference {
|
||||
return value === "gnome-libsecret" ||
|
||||
value === "kwallet" ||
|
||||
value === "kwallet5" ||
|
||||
value === "kwallet6"
|
||||
? value
|
||||
: DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
|
||||
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
|
||||
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
|
||||
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
|
||||
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
|
||||
// specific one sets linuxPasswordStore explicitly.
|
||||
export function resolveLinuxPasswordStoreSwitch(input: {
|
||||
readonly preference: LinuxPasswordStorePreference;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): LinuxPasswordStoreSwitch | null {
|
||||
if (input.preference !== "auto") {
|
||||
return input.preference;
|
||||
}
|
||||
|
||||
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
|
||||
}
|
||||
|
||||
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
|
||||
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
|
||||
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
|
||||
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
|
||||
// it lands on the same backend.
|
||||
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
|
||||
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveLinuxSecretStorageUnavailableMessage(input: {
|
||||
readonly configuredPreference: LinuxPasswordStorePreference;
|
||||
readonly selectedBackend: string | null;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): string {
|
||||
if (input.configuredPreference === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
input.configuredPreference === "kwallet" ||
|
||||
input.configuredPreference === "kwallet5" ||
|
||||
input.configuredPreference === "kwallet6"
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
|
||||
if (backend === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
backend === "kwallet" ||
|
||||
backend === "kwallet5" ||
|
||||
backend === "kwallet6" ||
|
||||
looksLikeKdeSession(input.env)
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
function getGnomeKeyringRemediationMessage(): string {
|
||||
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
|
||||
}
|
||||
|
||||
function getKWalletRemediationMessage(): string {
|
||||
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
|
||||
}
|
||||
|
||||
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
|
||||
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
|
||||
// rather than an unprotected credential store.
|
||||
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
|
||||
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
|
||||
if (currentDesktopNames.length > 0) {
|
||||
return currentDesktopNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
const legacyNames = legacyDesktopNames(env);
|
||||
if (legacyNames.length > 0) {
|
||||
return legacyNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
|
||||
}
|
||||
|
||||
function isKdeDesktopName(name: string): boolean {
|
||||
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
|
||||
}
|
||||
|
||||
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
|
||||
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonEmptyDesktopNames(value: string | undefined): string[] {
|
||||
return splitDesktopNameList(value).flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function isSet(value: string | undefined): boolean {
|
||||
return Boolean(value?.trim());
|
||||
}
|
||||
|
||||
function isAffirmativeFlag(value: string | undefined): boolean {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
|
||||
}
|
||||
|
||||
function splitDesktopNameList(value: string | undefined): string[] {
|
||||
return value?.split(":") ?? [];
|
||||
}
|
||||
|
||||
function normalizeDesktopName(value: string | undefined): string | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedStorageBackend(value: string | null): string | null {
|
||||
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -42,22 +43,26 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "./wsl/DesktopWslServerTree.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -113,6 +118,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -160,6 +166,8 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(DesktopWslServerTree.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
@@ -177,6 +185,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
@@ -191,16 +200,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
);
|
||||
|
||||
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
|
||||
// yield and let Electron emit ready.
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
),
|
||||
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
|
||||
),
|
||||
Layer.provideMerge(DesktopPreReadyPlatform.layer),
|
||||
);
|
||||
|
||||
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -97,7 +97,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) =>
|
||||
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
|
||||
const keyboardEvent = (
|
||||
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
|
||||
) => ({
|
||||
key: "Enter",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
isComposing: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("resolveAnnotationSubmission", () => {
|
||||
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
|
||||
});
|
||||
|
||||
it("leaves Shift+Enter and composition events available for editing", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
|
||||
|
||||
interface AnnotationKeyboardEvent {
|
||||
readonly key: string;
|
||||
readonly metaKey: boolean;
|
||||
readonly ctrlKey: boolean;
|
||||
readonly shiftKey: boolean;
|
||||
readonly isComposing: boolean;
|
||||
}
|
||||
|
||||
export function resolveAnnotationSubmission(
|
||||
event: AnnotationKeyboardEvent,
|
||||
): PreviewAnnotationSubmission | null {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
|
||||
return event.metaKey || event.ctrlKey ? "send" : "attach";
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
|
||||
// and silently granting it would hand every page the user's installed-font
|
||||
// fingerprint (and font file bytes via FontData.blob()). The app's own font
|
||||
// picker runs in the main window session, which is unaffected by this list.
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
|
||||
@@ -0,0 +1,999 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MAX_FAVICON_CANDIDATES,
|
||||
MAX_FAVICON_RESPONSE_BYTES,
|
||||
captureFavicon,
|
||||
selectFaviconCandidates,
|
||||
} from "./FaviconCapture.ts";
|
||||
|
||||
const PNG = "data:image/png;base64,cG5n";
|
||||
const SOURCE_PNG = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
|
||||
SOURCE_PNG.writeUInt32BE(1, 16);
|
||||
SOURCE_PNG.writeUInt32BE(1, 20);
|
||||
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
|
||||
|
||||
function sourceGif(
|
||||
width: number,
|
||||
height: number,
|
||||
frameWidth = width,
|
||||
frameHeight = height,
|
||||
additionalFrames: ReadonlyArray<{
|
||||
readonly left?: number;
|
||||
readonly top?: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}> = [],
|
||||
): Buffer {
|
||||
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
|
||||
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
|
||||
buffer.write("GIF89a", 0, "ascii");
|
||||
buffer.writeUInt16LE(width, 6);
|
||||
buffer.writeUInt16LE(height, 8);
|
||||
let offset = 13;
|
||||
for (const frame of frames) {
|
||||
buffer[offset] = 0x2c;
|
||||
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
|
||||
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
|
||||
buffer.writeUInt16LE(frame.width, offset + 5);
|
||||
buffer.writeUInt16LE(frame.height, offset + 7);
|
||||
offset += 10;
|
||||
buffer[offset] = 2;
|
||||
buffer[offset + 1] = 0;
|
||||
offset += 2;
|
||||
}
|
||||
buffer[offset] = 0x3b;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceJpeg(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: number | ReadonlyArray<number> = [],
|
||||
): Buffer {
|
||||
const frame = Buffer.from([
|
||||
0xff,
|
||||
0xd8,
|
||||
0xff,
|
||||
0xc0,
|
||||
0x00,
|
||||
0x07,
|
||||
0x08,
|
||||
height >>> 8,
|
||||
height & 0xff,
|
||||
width >>> 8,
|
||||
width & 0xff,
|
||||
]);
|
||||
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
|
||||
(orientation) => sourceJpegExifSegment([orientation]),
|
||||
);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegApp1Segment(payload: Buffer): Buffer {
|
||||
const app1 = Buffer.alloc(4 + payload.byteLength);
|
||||
app1[0] = 0xff;
|
||||
app1[1] = 0xe1;
|
||||
app1.writeUInt16BE(payload.byteLength + 2, 2);
|
||||
payload.copy(app1, 4);
|
||||
return app1;
|
||||
}
|
||||
|
||||
function sourceJpegExifSegment(
|
||||
orientations: ReadonlyArray<number>,
|
||||
options?: {
|
||||
readonly byteOrder?: "II" | "MM";
|
||||
readonly magic?: number;
|
||||
readonly padding?: number;
|
||||
},
|
||||
): Buffer {
|
||||
const exif = Buffer.alloc(20 + orientations.length * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif[5] = options?.padding ?? 0;
|
||||
const littleEndian = options?.byteOrder !== "MM";
|
||||
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
|
||||
const writeUInt16 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
|
||||
const writeUInt32 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
|
||||
writeUInt16(options?.magic ?? 42, 8);
|
||||
writeUInt32(8, 10);
|
||||
writeUInt16(orientations.length, 14);
|
||||
orientations.forEach((orientation, index) => {
|
||||
const entryOffset = 16 + index * 12;
|
||||
writeUInt16(0x0112, entryOffset);
|
||||
writeUInt16(3, entryOffset + 2);
|
||||
writeUInt32(1, entryOffset + 4);
|
||||
writeUInt16(orientation, entryOffset + 8);
|
||||
});
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegWithApp1Segments(
|
||||
width: number,
|
||||
height: number,
|
||||
segments: ReadonlyArray<Buffer>,
|
||||
): Buffer {
|
||||
const frame = sourceJpeg(width, height);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithOrientationEntries(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: ReadonlyArray<number>,
|
||||
): Buffer {
|
||||
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
|
||||
const exif = sourceJpegExifSegment([6], { byteOrder });
|
||||
exif[10] = alias;
|
||||
exif[11] = alias;
|
||||
return sourceJpegWithApp1Segments(64, 32, [exif]);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfd(options: {
|
||||
readonly rootOrientation?: number;
|
||||
readonly subIfdFirst?: boolean;
|
||||
readonly subIfdOrientation: number;
|
||||
}): Buffer {
|
||||
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
|
||||
const rootIfdOffset = 14;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
|
||||
const writeOrientation = (offset: number, orientation: number) => {
|
||||
exif.writeUInt16LE(0x0112, offset);
|
||||
exif.writeUInt16LE(3, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt16LE(orientation, offset + 8);
|
||||
};
|
||||
const writeSubIfdPointer = (offset: number) => {
|
||||
exif.writeUInt16LE(0x8769, offset);
|
||||
exif.writeUInt16LE(4, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
|
||||
};
|
||||
|
||||
const firstRootEntryOffset = rootIfdOffset + 2;
|
||||
if (options.rootOrientation === undefined) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
} else if (options.subIfdFirst) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
|
||||
} else {
|
||||
writeOrientation(firstRootEntryOffset, options.rootOrientation);
|
||||
writeSubIfdPointer(firstRootEntryOffset + 12);
|
||||
}
|
||||
|
||||
exif.writeUInt16LE(1, subIfdOffset);
|
||||
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfdPointers(options: {
|
||||
readonly pointerCount: number;
|
||||
readonly subIfdEntries: number;
|
||||
}): Buffer {
|
||||
const { pointerCount, subIfdEntries } = options;
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
|
||||
for (let index = 0; index < subIfdEntries; index += 1) {
|
||||
const entryOffset = subIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(1, entryOffset);
|
||||
exif.writeUInt16LE(3, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
}
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceWebp(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.alloc(30);
|
||||
buffer.write("RIFF", 0, "ascii");
|
||||
buffer.write("WEBP", 8, "ascii");
|
||||
buffer.write("VP8X", 12, "ascii");
|
||||
buffer.writeUIntLE(width - 1, 24, 3);
|
||||
buffer.writeUIntLE(height - 1, 27, 3);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceIco(embedded: Buffer): Buffer {
|
||||
const buffer = Buffer.alloc(22 + embedded.byteLength);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(embedded.byteLength, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
embedded.copy(buffer, 22);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafePng(): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(4096, 16);
|
||||
buffer.writeUInt32BE(4096, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourcePng(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafeDib(): Buffer {
|
||||
const buffer = Buffer.alloc(40);
|
||||
buffer.writeUInt32LE(40, 0);
|
||||
buffer.writeInt32LE(4096, 4);
|
||||
buffer.writeInt32LE(4096, 8);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeWebContents(options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
}) {
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
|
||||
);
|
||||
return {
|
||||
webContents: {
|
||||
session: { fetch },
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
} as never,
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
};
|
||||
}
|
||||
|
||||
const JPEG_LANDSCAPE_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
resizeHeight: 16,
|
||||
resizeWidth: 32,
|
||||
} as const;
|
||||
const JPEG_PORTRAIT_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
resizeHeight: 32,
|
||||
resizeWidth: 16,
|
||||
} as const;
|
||||
|
||||
async function expectJpegLayout(
|
||||
source: Buffer,
|
||||
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
|
||||
): Promise<void> {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
|
||||
expect(code).toContain(layout.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
describe("selectFaviconCandidates", () => {
|
||||
it("filters and deduplicates before applying the candidate cap", () => {
|
||||
const valid = Array.from(
|
||||
{ length: MAX_FAVICON_CANDIDATES + 2 },
|
||||
(_, index) => `https://example.com/favicon-${index}.png`,
|
||||
);
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
|
||||
valid[0]!,
|
||||
valid[0]!,
|
||||
...valid.slice(1),
|
||||
]),
|
||||
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
|
||||
});
|
||||
|
||||
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
|
||||
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 128 }, () => oversizedInvalid),
|
||||
"https://example.com/too-late.png",
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("captureFavicon", () => {
|
||||
it.each([
|
||||
{
|
||||
label: "same-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
credentials: "include",
|
||||
},
|
||||
{
|
||||
label: "cross-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://cdn.example.net/favicon.png",
|
||||
credentials: "omit",
|
||||
},
|
||||
])("uses the explicit credential policy for $label requests", async (testCase) => {
|
||||
const { webContents, fetch } = makeWebContents();
|
||||
const result = await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: testCase.pageUrl,
|
||||
candidates: [testCase.faviconUrl],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
testCase.faviconUrl,
|
||||
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("decodes base64 and percent-encoded inline images without fetching", async () => {
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const percentEncodedPng = [...SOURCE_PNG]
|
||||
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
|
||||
.join("");
|
||||
|
||||
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("tries the next candidate after an ordinary rejection", async () => {
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(null, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("cancels a rejected response body before trying the next candidate", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(body, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("stops a pending fetch when its capture is aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: (_url, init) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
expect(await capture).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("ends candidate fallback when the overall capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: (url, init) => {
|
||||
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [
|
||||
"https://example.com/first.png",
|
||||
"https://example.com/second.png",
|
||||
"https://example.com/third.png",
|
||||
],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(timeout).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not publish a rasterization that completes after the capture deadline", async () => {
|
||||
const captureTimeoutController = new AbortController();
|
||||
const rasterTimeoutController = new AbortController();
|
||||
const timeout = vi
|
||||
.spyOn(AbortSignal, "timeout")
|
||||
.mockImplementation((milliseconds) =>
|
||||
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
|
||||
);
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
|
||||
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a stalled response body when the capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const cancel = vi.fn();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
cancel,
|
||||
}),
|
||||
{ headers: { "content-type": "image/png" } },
|
||||
),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects and cancels an oversized streamed response", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains bounded compatibility with common favicon formats", async () => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
for (const [mime, buffer] of [
|
||||
["image/gif", sourceGif(32, 32)],
|
||||
["image/jpeg", sourceJpeg(32, 32)],
|
||||
["image/webp", sourceWebp(32, 32)],
|
||||
["image/x-icon", sourceIco(SOURCE_PNG)],
|
||||
] as const) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "landscape",
|
||||
source: sourcePng(64, 32),
|
||||
resizeWidth: 32,
|
||||
resizeHeight: 16,
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
},
|
||||
{
|
||||
label: "portrait",
|
||||
source: sourcePng(32, 64),
|
||||
resizeWidth: 16,
|
||||
resizeHeight: 32,
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
},
|
||||
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
|
||||
expect(code).toContain('resizeQuality: "high"');
|
||||
expect(code).toContain(testCase.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
});
|
||||
|
||||
it.each([
|
||||
...[1, 2, 3, 4].map((orientation) => ({
|
||||
label: `keeps stored dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
...[5, 6, 7, 8].map((orientation) => ({
|
||||
label: `uses display dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is transposed",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [6, 1]),
|
||||
},
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is untransposed",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [1, 6]),
|
||||
},
|
||||
{
|
||||
label: "does not consult a later EXIF segment after an invalid orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "uses a later valid orientation in the same IFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "skips a non-EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("not-exif")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "skips an empty EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "stops after a malformed qualifying EXIF APP1 segment",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "ignores the EXIF padding byte",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
|
||||
},
|
||||
{
|
||||
label: "reads big-endian EXIF",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
|
||||
},
|
||||
{
|
||||
label: "matches Chromium for a nonstandard TIFF magic field",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit little-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xc9, "II"),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit big-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xcd, "MM"),
|
||||
},
|
||||
{
|
||||
label: "reads an orientation from a SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a SubIFD orientation before a later root orientation",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({
|
||||
rootOrientation: 1,
|
||||
subIfdFirst: true,
|
||||
subIfdOrientation: 6,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a root orientation before a later SubIFD orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "memoizes repeated aliases to the same SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
|
||||
]),
|
||||
},
|
||||
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
|
||||
await expectJpegLayout(source, layout);
|
||||
});
|
||||
|
||||
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
|
||||
const source = sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithOverlappingSubIfds(32, 32),
|
||||
]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
|
||||
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unsafe PNG size before rasterization", async () => {
|
||||
const buffer = makeUnsafePng();
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(new Uint8Array(buffer), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["GIF", "image/gif", sourceGif(4096, 4096)],
|
||||
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
|
||||
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
|
||||
[
|
||||
"GIF cumulative frames",
|
||||
"image/gif",
|
||||
sourceGif(
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
|
||||
),
|
||||
],
|
||||
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
|
||||
["WebP", "image/webp", sourceWebp(4096, 4096)],
|
||||
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
|
||||
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
|
||||
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
|
||||
[
|
||||
"SVG with embedded bitmap",
|
||||
"image/svg+xml",
|
||||
Buffer.from(
|
||||
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
|
||||
),
|
||||
],
|
||||
[
|
||||
"ICO invalid payload span",
|
||||
"image/x-icon",
|
||||
(() => {
|
||||
const buffer = Buffer.alloc(22);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(100, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
return buffer;
|
||||
})(),
|
||||
],
|
||||
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores output that is not a bounded PNG data URL", async () => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("waits for physical rasterization settlement after a logical timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveOld!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveOld = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const timedOut = captureFavicon(input);
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
expect(await timedOut).toEqual({ kind: "timed-out" });
|
||||
|
||||
const newer = captureFavicon(input);
|
||||
await Promise.resolve();
|
||||
expect(executions).toBe(1);
|
||||
resolveOld(PNG);
|
||||
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ends candidate fallback after a rasterization timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
|
||||
let resolveFirst!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const first = captureFavicon(input);
|
||||
const superseded = captureFavicon(input);
|
||||
const newest = captureFavicon(input);
|
||||
|
||||
expect(executions).toBe(1);
|
||||
resolveFirst(PNG);
|
||||
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(await superseded).toEqual({ kind: "none" });
|
||||
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,679 @@
|
||||
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
|
||||
export const MAX_FAVICON_CANDIDATES = 8;
|
||||
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
|
||||
|
||||
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
|
||||
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
|
||||
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
|
||||
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
|
||||
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
|
||||
const FAVICON_RASTER_WORLD_ID = 1001;
|
||||
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
interface RasterizationGate {
|
||||
generation: number;
|
||||
launchAllowed?: Promise<void>;
|
||||
}
|
||||
|
||||
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
|
||||
|
||||
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const finish = () => {
|
||||
signal.removeEventListener("abort", finish);
|
||||
resolve();
|
||||
};
|
||||
signal.addEventListener("abort", finish, { once: true });
|
||||
void previous.then(finish);
|
||||
});
|
||||
}
|
||||
|
||||
export type FaviconCaptureResult =
|
||||
| { readonly kind: "captured"; readonly dataUrl: string }
|
||||
| { readonly kind: "none" }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
type RasterizationResult =
|
||||
| { readonly kind: "completed"; readonly value: unknown }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
export function safeHttpOrigin(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
|
||||
const selected: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let inputUnits = 0;
|
||||
for (const candidate of candidates) {
|
||||
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
|
||||
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
|
||||
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
|
||||
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
|
||||
seen.add(candidate);
|
||||
selected.push(candidate);
|
||||
if (selected.length === MAX_FAVICON_CANDIDATES) break;
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
export async function captureFavicon(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageUrl: string;
|
||||
readonly candidates: ReadonlyArray<string>;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
if (!pageOrigin) return { kind: "none" };
|
||||
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
|
||||
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
|
||||
|
||||
for (const candidate of selectFaviconCandidates(input.candidates)) {
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
const captured = await captureCandidate({
|
||||
webContents: input.webContents,
|
||||
pageOrigin,
|
||||
candidate,
|
||||
signal: captureSignal,
|
||||
});
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
|
||||
}
|
||||
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
async function captureCandidate(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageOrigin: string;
|
||||
readonly candidate: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
try {
|
||||
const inline = parseInlineFavicon(input.candidate);
|
||||
if (inline) {
|
||||
return await normalizeFaviconBuffer(
|
||||
input.webContents,
|
||||
inline.mime,
|
||||
inline.buffer,
|
||||
input.signal,
|
||||
);
|
||||
}
|
||||
|
||||
const candidateOrigin = safeHttpOrigin(input.candidate);
|
||||
if (!candidateOrigin) return { kind: "none" };
|
||||
const response = await input.webContents.session.fetch(input.candidate, {
|
||||
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
|
||||
redirect: "error",
|
||||
signal: input.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
return { kind: "none" };
|
||||
}
|
||||
const buffer = await readFaviconResponse(response, input.signal);
|
||||
if (!buffer || input.signal.aborted) return { kind: "none" };
|
||||
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
|
||||
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
|
||||
} catch {
|
||||
return { kind: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
async function readFaviconResponse(
|
||||
response: Response,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | null> {
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await response.body?.cancel();
|
||||
return null;
|
||||
}
|
||||
if (!response.body) {
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const cancelForAbort = () => {
|
||||
void reader.cancel(signal.reason).catch(() => undefined);
|
||||
};
|
||||
signal.addEventListener("abort", cancelForAbort, { once: true });
|
||||
if (signal.aborted) cancelForAbort();
|
||||
const chunks: Buffer[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read();
|
||||
if (next.done) return Buffer.concat(chunks, byteLength);
|
||||
byteLength += next.value.byteLength;
|
||||
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await reader.cancel();
|
||||
return null;
|
||||
}
|
||||
chunks.push(Buffer.from(next.value));
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancelForAbort);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function isSupportedFaviconUrl(url: string): boolean {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
|
||||
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
|
||||
try {
|
||||
const protocol = new URL(url).protocol;
|
||||
return (
|
||||
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeInlineFaviconPayload(payload: string): Buffer | null {
|
||||
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
|
||||
let inputOffset = 0;
|
||||
let outputOffset = 0;
|
||||
while (inputOffset < payload.length) {
|
||||
const escapeOffset = payload.indexOf("%", inputOffset);
|
||||
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
|
||||
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
|
||||
if (escapeOffset === -1) break;
|
||||
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
|
||||
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
|
||||
decoded[outputOffset] = Number.parseInt(hex, 16);
|
||||
outputOffset += 1;
|
||||
inputOffset = escapeOffset + 3;
|
||||
}
|
||||
return decoded.subarray(0, outputOffset);
|
||||
}
|
||||
|
||||
function parseInlineFavicon(
|
||||
url: string,
|
||||
): { readonly buffer: Buffer; readonly mime: string } | null {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
|
||||
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
|
||||
if (!match) return null;
|
||||
const mime = match[1]?.toLowerCase();
|
||||
const parameters = match[2]
|
||||
?.split(";")
|
||||
.filter(Boolean)
|
||||
.map((parameter) => parameter.toLowerCase());
|
||||
const payload = match[3];
|
||||
if (!mime || !parameters || !payload) return null;
|
||||
const base64 = parameters.at(-1) === "base64";
|
||||
if (parameters.includes("base64") && !base64) return null;
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
if (base64) {
|
||||
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
|
||||
buffer = Buffer.from(payload, "base64");
|
||||
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const decoded = decodeInlineFaviconPayload(payload);
|
||||
if (!decoded) return null;
|
||||
buffer = decoded;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
|
||||
? { buffer, mime }
|
||||
: null;
|
||||
}
|
||||
|
||||
interface ImageDimensions {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
|
||||
return (
|
||||
dimensions !== null &&
|
||||
Number.isSafeInteger(dimensions.width) &&
|
||||
Number.isSafeInteger(dimensions.height) &&
|
||||
dimensions.width > 0 &&
|
||||
dimensions.height > 0 &&
|
||||
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
|
||||
);
|
||||
}
|
||||
|
||||
function pngDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
|
||||
return null;
|
||||
}
|
||||
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
|
||||
}
|
||||
|
||||
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
|
||||
let offset = startOffset;
|
||||
while (offset < buffer.byteLength) {
|
||||
const blockLength = buffer[offset]!;
|
||||
offset += 1;
|
||||
if (blockLength === 0) return offset;
|
||||
if (offset + blockLength > buffer.byteLength) return null;
|
||||
offset += blockLength;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function gifDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
|
||||
return null;
|
||||
}
|
||||
const logicalWidth = buffer.readUInt16LE(6);
|
||||
const logicalHeight = buffer.readUInt16LE(8);
|
||||
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
|
||||
const packed = buffer[10]!;
|
||||
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
|
||||
if (offset > buffer.byteLength) return null;
|
||||
let width = logicalWidth;
|
||||
let height = logicalHeight;
|
||||
let frameCount = 0;
|
||||
let framePixels = 0;
|
||||
while (offset < buffer.byteLength) {
|
||||
const marker = buffer[offset];
|
||||
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
|
||||
if (marker === 0x2c) {
|
||||
if (offset + 10 > buffer.byteLength) return null;
|
||||
const left = buffer.readUInt16LE(offset + 1);
|
||||
const top = buffer.readUInt16LE(offset + 3);
|
||||
const frameWidth = buffer.readUInt16LE(offset + 5);
|
||||
const frameHeight = buffer.readUInt16LE(offset + 7);
|
||||
if (frameWidth === 0 || frameHeight === 0) return null;
|
||||
framePixels += frameWidth * frameHeight;
|
||||
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
|
||||
width = Math.max(width, left + frameWidth);
|
||||
height = Math.max(height, top + frameHeight);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const framePacked = buffer[offset + 9]!;
|
||||
offset += 10;
|
||||
if ((framePacked & 0x80) !== 0) {
|
||||
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
|
||||
}
|
||||
if (offset >= buffer.byteLength) return null;
|
||||
const minimumCodeSize = buffer[offset]!;
|
||||
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
|
||||
offset += 1;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
frameCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface JpegExifMetadata {
|
||||
readonly complete: boolean;
|
||||
readonly orientation: number | null;
|
||||
}
|
||||
|
||||
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
|
||||
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
|
||||
return null;
|
||||
}
|
||||
const metadataWithoutOrientation = (): JpegExifMetadata => ({
|
||||
complete: true,
|
||||
orientation: null,
|
||||
});
|
||||
if (segment.byteLength < 14) return metadataWithoutOrientation();
|
||||
const tiffOffset = 6;
|
||||
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
|
||||
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
|
||||
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
|
||||
const readUInt16 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 2 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
|
||||
};
|
||||
const readUInt32 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 4 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
|
||||
};
|
||||
const relativeIfdOffset = readUInt32(tiffOffset + 4);
|
||||
if (relativeIfdOffset === null) return metadataWithoutOrientation();
|
||||
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
|
||||
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
|
||||
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
|
||||
type IfdOrientation = number | null | typeof budgetExhausted;
|
||||
const subIfdOrientationByOffset = new Map<number, number | null>();
|
||||
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
|
||||
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
|
||||
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
|
||||
}
|
||||
const entryCount = readUInt16(ifdOffset);
|
||||
if (entryCount === null) return null;
|
||||
let result: IfdOrientation = null;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (remainingIfdEntryVisits === 0) return budgetExhausted;
|
||||
remainingIfdEntryVisits -= 1;
|
||||
const entryOffset = ifdOffset + 2 + index * 12;
|
||||
if (entryOffset + 12 > segment.byteLength) break;
|
||||
const tag = readUInt16(entryOffset);
|
||||
const type = readUInt16(entryOffset + 2);
|
||||
const count = readUInt32(entryOffset + 4);
|
||||
if (tag === 0x0112 && type === 3 && count === 1) {
|
||||
const orientation = readUInt16(entryOffset + 8);
|
||||
if (orientation !== null && orientation >= 1 && orientation <= 8) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
|
||||
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
|
||||
if (relativeSubIfdOffset !== null) {
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
|
||||
if (orientation === budgetExhausted) return budgetExhausted;
|
||||
if (orientation !== null) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
|
||||
return result;
|
||||
};
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
|
||||
return orientation === budgetExhausted
|
||||
? { complete: false, orientation: null }
|
||||
: { complete: true, orientation };
|
||||
}
|
||||
|
||||
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
|
||||
const startOfFrameMarkers = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
|
||||
]);
|
||||
let offset = 2;
|
||||
let dimensions: ImageDimensions | null = null;
|
||||
let exifMetadata: JpegExifMetadata | null = null;
|
||||
while (offset + 3 < buffer.byteLength) {
|
||||
if (buffer[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
while (buffer[offset] === 0xff) offset += 1;
|
||||
const marker = buffer[offset];
|
||||
offset += 1;
|
||||
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
||||
if (offset + 1 >= buffer.byteLength) return null;
|
||||
const length = buffer.readUInt16BE(offset);
|
||||
if (length < 2 || offset + length > buffer.byteLength) return null;
|
||||
if (marker === 0xe1 && exifMetadata === null) {
|
||||
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
|
||||
}
|
||||
if (startOfFrameMarkers.has(marker)) {
|
||||
if (length < 7) return null;
|
||||
if (dimensions !== null) return null;
|
||||
dimensions = {
|
||||
height: buffer.readUInt16BE(offset + 3),
|
||||
width: buffer.readUInt16BE(offset + 5),
|
||||
};
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
if (!dimensions) return null;
|
||||
if (exifMetadata?.complete === false) return null;
|
||||
const orientation = exifMetadata?.orientation;
|
||||
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
|
||||
? { width: dimensions.height, height: dimensions.width }
|
||||
: dimensions;
|
||||
}
|
||||
|
||||
function webpDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 30 ||
|
||||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
|
||||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const kind = buffer.subarray(12, 16).toString("ascii");
|
||||
if (kind === "VP8X") {
|
||||
return {
|
||||
width: 1 + buffer.readUIntLE(24, 3),
|
||||
height: 1 + buffer.readUIntLE(27, 3),
|
||||
};
|
||||
}
|
||||
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(26) & 0x3fff,
|
||||
height: buffer.readUInt16LE(28) & 0x3fff,
|
||||
};
|
||||
}
|
||||
if (kind === "VP8L" && buffer[20] === 0x2f) {
|
||||
return {
|
||||
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
|
||||
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function dibDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 12) return null;
|
||||
const headerSize = buffer.readUInt32LE(0);
|
||||
if (headerSize === 12) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(4),
|
||||
height: buffer.readUInt16LE(6),
|
||||
};
|
||||
}
|
||||
if (headerSize < 40 || buffer.byteLength < 12) return null;
|
||||
return {
|
||||
width: Math.abs(buffer.readInt32LE(4)),
|
||||
height: Math.abs(buffer.readInt32LE(8)),
|
||||
};
|
||||
}
|
||||
|
||||
function icoDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 22 ||
|
||||
buffer.readUInt16LE(0) !== 0 ||
|
||||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const count = buffer.readUInt16LE(4);
|
||||
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = 6 + index * 16;
|
||||
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
|
||||
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const byteLength = buffer.readUInt32LE(offset + 8);
|
||||
const imageOffset = buffer.readUInt32LE(offset + 12);
|
||||
if (
|
||||
byteLength === 0 ||
|
||||
imageOffset < 6 + count * 16 ||
|
||||
imageOffset > buffer.byteLength ||
|
||||
byteLength > buffer.byteLength - imageOffset
|
||||
)
|
||||
return null;
|
||||
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
|
||||
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
|
||||
if (!safeDimensions(embeddedDimensions)) return null;
|
||||
}
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
return (
|
||||
pngDimensions(buffer) ??
|
||||
gifDimensions(buffer) ??
|
||||
jpegDimensions(buffer) ??
|
||||
webpDimensions(buffer) ??
|
||||
icoDimensions(buffer)
|
||||
);
|
||||
}
|
||||
|
||||
async function normalizeFaviconBuffer(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
signal: AbortSignal,
|
||||
): Promise<FaviconCaptureResult> {
|
||||
const declaredMime = mime?.trim().toLowerCase() || null;
|
||||
const normalizedMime =
|
||||
declaredMime === "application/x-icon"
|
||||
? "image/x-icon"
|
||||
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
|
||||
? null
|
||||
: declaredMime;
|
||||
const dimensions = sourceDimensions(buffer);
|
||||
if (
|
||||
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
|
||||
normalizedMime === "image/svg+xml" ||
|
||||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
|
||||
!safeDimensions(dimensions)
|
||||
) {
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
const rasterized = await rasterizeFavicon(
|
||||
webContents,
|
||||
normalizedMime,
|
||||
buffer,
|
||||
dimensions,
|
||||
signal,
|
||||
);
|
||||
if (rasterized.kind === "timed-out") return rasterized;
|
||||
return typeof rasterized.value === "string" &&
|
||||
rasterized.value.startsWith("data:image/png;base64,") &&
|
||||
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
|
||||
? { kind: "captured", dataUrl: rasterized.value }
|
||||
: { kind: "none" };
|
||||
}
|
||||
|
||||
async function rasterizeFavicon(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
dimensions: ImageDimensions,
|
||||
signal: AbortSignal,
|
||||
): Promise<RasterizationResult> {
|
||||
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
|
||||
rasterizationGates.set(webContents, gate);
|
||||
const generation = ++gate.generation;
|
||||
const previousLaunchAllowed = gate.launchAllowed;
|
||||
if (previousLaunchAllowed) {
|
||||
await waitForRasterLaunch(previousLaunchAllowed, signal);
|
||||
}
|
||||
if (signal.aborted || generation !== gate.generation) {
|
||||
return { kind: "completed", value: null };
|
||||
}
|
||||
|
||||
const payload = buffer.toString("base64");
|
||||
const blobType = mime ?? "";
|
||||
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
|
||||
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
|
||||
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
|
||||
const drawX = (32 - decodeWidth) / 2;
|
||||
const drawY = (32 - decodeHeight) / 2;
|
||||
const code = `
|
||||
(() => {
|
||||
const rasterize = async () => {
|
||||
try {
|
||||
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
|
||||
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
|
||||
resizeWidth: ${decodeWidth},
|
||||
resizeHeight: ${decodeHeight},
|
||||
resizeQuality: "high",
|
||||
});
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
|
||||
return null;
|
||||
}
|
||||
const canvas = new OffscreenCanvas(32, 32);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
|
||||
const blob = await canvas.convertToBlob({ type: "image/png" });
|
||||
const output = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = "";
|
||||
for (const byte of output) binary += String.fromCharCode(byte);
|
||||
return "data:image/png;base64," + btoa(binary);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return rasterize();
|
||||
})()
|
||||
`;
|
||||
|
||||
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
|
||||
{ code },
|
||||
]);
|
||||
|
||||
const result = new Promise<RasterizationResult>((resolve, reject) => {
|
||||
// Electron cannot cancel isolated-world execution. This timeout ends only
|
||||
// the logical attempt; renderer work may finish after a newer attempt starts.
|
||||
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
|
||||
let settled = false;
|
||||
const finish = (complete: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
timeout.removeEventListener("abort", onTimeout);
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
complete();
|
||||
};
|
||||
const onTimeout = () => {
|
||||
finish(() => resolve({ kind: "timed-out" }));
|
||||
};
|
||||
const onAbort = () => {
|
||||
finish(() => resolve({ kind: "completed", value: null }));
|
||||
};
|
||||
timeout.addEventListener("abort", onTimeout, { once: true });
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
void execution.then(
|
||||
(value) => {
|
||||
finish(() => resolve({ kind: "completed", value }));
|
||||
},
|
||||
(cause: unknown) => {
|
||||
finish(() => reject(cause));
|
||||
},
|
||||
);
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
// The logical timeout does not cancel Electron's renderer work. Keep the
|
||||
// gate closed until that physical execution actually settles.
|
||||
const launchAllowed = execution.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
gate.launchAllowed = launchAllowed;
|
||||
void launchAllowed.then(() => {
|
||||
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
|
||||
});
|
||||
return await result;
|
||||
}
|
||||
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPreviewRefreshShortcut", () => {
|
||||
const input = (overrides: Partial<Electron.Input> = {}) =>
|
||||
({
|
||||
type: "keyDown",
|
||||
key: "r",
|
||||
meta: true,
|
||||
control: false,
|
||||
shift: false,
|
||||
alt: false,
|
||||
...overrides,
|
||||
}) as Electron.Input;
|
||||
|
||||
it("recognizes the platform refresh chord without matching modified variants", () => {
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const {
|
||||
browserWindowConstructor,
|
||||
createFromPath,
|
||||
@@ -164,6 +186,102 @@ const makeTestPreviewWebContents = (
|
||||
capturePage,
|
||||
}) as never;
|
||||
|
||||
const TEST_FAVICON = "data:image/png;base64,cG5n";
|
||||
|
||||
const makeSourcePng = (width = 1, height = 1): Buffer => {
|
||||
const buffer = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
};
|
||||
|
||||
const makeFaviconWebContents = (options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly id?: number;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
readonly url?: string;
|
||||
}) => {
|
||||
const sourcePng = makeSourcePng();
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
let currentUrl = options?.url ?? "http://localhost:3200/";
|
||||
let destroyed = false;
|
||||
let loading = false;
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(sourcePng), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
|
||||
);
|
||||
const reload = vi.fn();
|
||||
const loadURL = vi.fn(async (url: string) => {
|
||||
currentUrl = url;
|
||||
});
|
||||
const off = vi.fn();
|
||||
const debuggerOff = vi.fn();
|
||||
const webContents = {
|
||||
id: options?.id ?? 42,
|
||||
isDestroyed: () => destroyed,
|
||||
getType: () => "webview",
|
||||
getURL: () => currentUrl,
|
||||
getTitle: () => "Preview",
|
||||
isLoading: () => loading,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
reload,
|
||||
reloadIgnoringCache: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off,
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
session: { fetch },
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: debuggerOff,
|
||||
},
|
||||
};
|
||||
return {
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
debuggerOff,
|
||||
listeners,
|
||||
loadURL,
|
||||
off,
|
||||
reload,
|
||||
setDestroyed: (value: boolean) => {
|
||||
destroyed = value;
|
||||
},
|
||||
setLoading: (value: boolean) => {
|
||||
loading = value;
|
||||
},
|
||||
setUrl: (url: string) => {
|
||||
currentUrl = url;
|
||||
},
|
||||
webContents: webContents as never,
|
||||
};
|
||||
};
|
||||
|
||||
const settle = function* (until: () => boolean) {
|
||||
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
};
|
||||
|
||||
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
|
||||
const listeners = new Map<string, () => void>();
|
||||
const send = vi.fn();
|
||||
@@ -235,6 +353,32 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("rejects a destroyed webview during registration", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const getType = vi.fn(() => "webview" as const);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => true,
|
||||
getType,
|
||||
} as never);
|
||||
yield* manager.createTab("tab_destroyed_registration");
|
||||
|
||||
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
|
||||
_tag: "PreviewWebContentsNotFoundError",
|
||||
tabId: "tab_destroyed_registration",
|
||||
webContentsId: 42,
|
||||
});
|
||||
}
|
||||
expect(getType).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
@@ -353,6 +497,488 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_destroyed_navigation");
|
||||
yield* manager.registerWebview("tab_destroyed_navigation", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
|
||||
preview.setDestroyed(true);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
|
||||
|
||||
expect(preview.loadURL).not.toHaveBeenCalled();
|
||||
expect(preview.reload).not.toHaveBeenCalled();
|
||||
expect(preview.off).toHaveBeenCalled();
|
||||
expect(preview.debuggerOff).toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: null,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const previous = makeFaviconWebContents();
|
||||
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
|
||||
let current = previous.webContents;
|
||||
let startReplacementRegistration: () => void = () => void 0;
|
||||
const replacementReady = new Promise<void>((resolve) => {
|
||||
startReplacementRegistration = resolve;
|
||||
});
|
||||
fromId.mockImplementation(() => current);
|
||||
yield* manager.createTab("tab_destroyed_replacement_race");
|
||||
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
|
||||
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
|
||||
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
previous.setDestroyed(true);
|
||||
previous.debuggerOff.mockImplementationOnce(() => {
|
||||
current = replacement.webContents;
|
||||
startReplacementRegistration();
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
|
||||
const registrationExit = yield* Fiber.await(replacementRegistration);
|
||||
|
||||
expect(Exit.isSuccess(registrationExit)).toBe(true);
|
||||
expect(previous.off).toHaveBeenCalled();
|
||||
expect(replacement.off).not.toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: 42,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents({
|
||||
url: `http://localhost:3200/${"x".repeat(3_000)}`,
|
||||
});
|
||||
preview.setLoading(true);
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_loading");
|
||||
yield* manager.registerWebview("tab_favicon_loading", 42);
|
||||
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(states.at(-1)?.favicon).toMatchObject({
|
||||
dataUrl: TEST_FAVICON,
|
||||
pageUrl: "http://localhost:3200",
|
||||
});
|
||||
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
const firstResponse = new Promise<Response>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: (url) =>
|
||||
url.endsWith("first.png")
|
||||
? firstResponse
|
||||
: Promise.resolve(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_latest");
|
||||
yield* manager.registerWebview("tab_favicon_latest", 42);
|
||||
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
resolveFirst(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(preview.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("allows an identical retry after an undecodable capture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let rasterizations = 0;
|
||||
const preview = makeFaviconWebContents({
|
||||
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_retry");
|
||||
yield* manager.registerWebview("tab_favicon_retry", 42);
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => rasterizations === 1);
|
||||
yield* settle(() => false);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(rasterizations).toBe(2);
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not publish a capture invalidated by navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_navigation");
|
||||
yield* manager.registerWebview("tab_favicon_navigation", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
preview.listeners.get("did-start-navigation")?.({
|
||||
isMainFrame: true,
|
||||
isSameDocument: false,
|
||||
} as never);
|
||||
preview.setUrl("https://example.com/");
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reload");
|
||||
yield* manager.registerWebview("tab_favicon_reload", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
|
||||
|
||||
expect(preview.reload).toHaveBeenCalledOnce();
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_origin");
|
||||
yield* manager.registerWebview("tab_favicon_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("https://example.com/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect(
|
||||
"retains the previous document icon across a failed cross-origin navigation",
|
||||
() =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_failed_origin");
|
||||
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.listeners.get("did-fail-load")?.(
|
||||
{} as never,
|
||||
-105 as never,
|
||||
"Name not resolved" as never,
|
||||
"https://unreachable.example/" as never,
|
||||
true as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_blank");
|
||||
yield* manager.registerWebview("tab_favicon_blank", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("about:blank");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
|
||||
preview.setUrl("http://localhost:3200/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) => {
|
||||
if (id === 42) return initial.webContents;
|
||||
if (id === 43) return replacement.webContents;
|
||||
return null;
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_replace");
|
||||
yield* manager.registerWebview("tab_favicon_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_replace", 43);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const initial = makeFaviconWebContents({
|
||||
id: 42,
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) =>
|
||||
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
|
||||
);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_late_replace");
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => initial.fetch.mock.calls.length === 1);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 43);
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(
|
||||
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
|
||||
).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 42 });
|
||||
let active = initial.webContents;
|
||||
fromId.mockImplementation(() => active);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reused_id");
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
active = replacement.webContents;
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
expect(initial.off).toHaveBeenCalled();
|
||||
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reregister");
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -982,6 +1608,92 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emits debugger screencast frames only while recording is active", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let debuggerMessage:
|
||||
| ((event: unknown, method: string, params: Record<string, unknown>) => void)
|
||||
| undefined;
|
||||
const capturePage = vi.fn(async () => ({
|
||||
toJPEG: () => Buffer.from("scheduled-recording-frame"),
|
||||
getSize: () => ({ width: 1280, height: 720 }),
|
||||
}));
|
||||
const sendCommand = vi.fn(async (method: string) =>
|
||||
method === "Runtime.evaluate" ? { result: { value: null } } : undefined,
|
||||
);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(
|
||||
(
|
||||
event: string,
|
||||
listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
|
||||
) => {
|
||||
if (event === "message") debuggerMessage = listener;
|
||||
},
|
||||
),
|
||||
off: vi.fn(),
|
||||
},
|
||||
capturePage,
|
||||
} as never);
|
||||
const recordingFrames: DesktopPreviewRecordingFrame[] = [];
|
||||
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
Effect.sync(() => {
|
||||
recordingFrames.push(frame);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_screencast_guard");
|
||||
yield* manager.registerWebview("tab_screencast_guard", 42);
|
||||
yield* manager.automationEvaluate("tab_screencast_guard", { expression: "null" });
|
||||
|
||||
debuggerMessage?.({}, "Page.screencastFrame", {
|
||||
sessionId: 1,
|
||||
data: "inactive-frame",
|
||||
metadata: { deviceWidth: 1280, deviceHeight: 720 },
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
expect(recordingFrames).toHaveLength(0);
|
||||
|
||||
yield* manager.startRecording("tab_screencast_guard");
|
||||
recordingFrames.length = 0;
|
||||
debuggerMessage?.({}, "Page.screencastFrame", {
|
||||
sessionId: 2,
|
||||
data: "active-frame",
|
||||
metadata: { deviceWidth: 1280, deviceHeight: 720 },
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(recordingFrames).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "tab_screencast_guard",
|
||||
data: "active-frame",
|
||||
width: 1280,
|
||||
height: 720,
|
||||
}),
|
||||
]);
|
||||
yield* manager.stopRecording("tab_screencast_guard");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares background frame capture between recording and picture-in-picture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewFavicon,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -61,6 +63,7 @@ import {
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -84,6 +87,7 @@ export interface PreviewTabState {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon?: DesktopPreviewFavicon;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -109,7 +113,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
|
||||
colorScheme: "light",
|
||||
radius: "0.625rem",
|
||||
@@ -345,7 +349,10 @@ type PreviewInputSignal =
|
||||
| { readonly kind: "key"; readonly key: string; readonly code: string };
|
||||
|
||||
interface ManagedListeners {
|
||||
readonly attachmentId: symbol;
|
||||
readonly cancelFaviconCapture: () => void;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly webContents: Electron.WebContents;
|
||||
}
|
||||
|
||||
type FrameCaptureConsumer = "picture-in-picture" | "recording";
|
||||
@@ -406,6 +413,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
|
||||
{ key: "w", meta: true, shift: false, control: false },
|
||||
]);
|
||||
|
||||
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
|
||||
input.type === "keyDown" &&
|
||||
input.key.toLowerCase() === "r" &&
|
||||
(input.meta || input.control) &&
|
||||
!input.shift &&
|
||||
!input.alt;
|
||||
|
||||
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
|
||||
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
|
||||
if (value.kind === "pointer") {
|
||||
@@ -605,6 +619,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
|
||||
tabId: string,
|
||||
state: PreviewTabState,
|
||||
) {
|
||||
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
|
||||
yield* emit(tabId, state);
|
||||
}
|
||||
});
|
||||
|
||||
const update = Effect.fn("PreviewManager.update")(function* (
|
||||
tabId: string,
|
||||
patch: Partial<PreviewTabState>,
|
||||
@@ -671,10 +694,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
),
|
||||
);
|
||||
|
||||
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
return (
|
||||
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
|
||||
);
|
||||
});
|
||||
|
||||
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
|
||||
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
|
||||
|
||||
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
|
||||
const captureDiagnosticMessage = Effect.fnUntraced(function* (
|
||||
webContentsId: number,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -852,11 +882,53 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
|
||||
function* (method: string, params: Record<string, unknown>) {
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
const handleDebuggerMessage = Effect.fnUntraced(function* (
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const captureSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(
|
||||
tabId,
|
||||
);
|
||||
if (captureSession?.consumers.has("recording")) {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width:
|
||||
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
});
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
runFork(handleDebuggerMessage(method, params));
|
||||
};
|
||||
@@ -1147,7 +1219,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
copy.delete(webContentsId);
|
||||
}),
|
||||
]);
|
||||
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
if (managed) {
|
||||
managed.cancelFaviconCapture();
|
||||
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const isAppShortcut = (input: Electron.Input): boolean =>
|
||||
@@ -1211,8 +1286,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const attachmentId = Symbol();
|
||||
let documentId = 0;
|
||||
let nextRequestId = 0;
|
||||
let activeCapture: {
|
||||
readonly controller: AbortController;
|
||||
readonly documentId: number;
|
||||
readonly eventKey: string;
|
||||
readonly requestId: number;
|
||||
} | null = null;
|
||||
const cancelFaviconCapture = () => {
|
||||
documentId += 1;
|
||||
activeCapture?.controller.abort();
|
||||
activeCapture = null;
|
||||
};
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
confirmedNavigation = false,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
@@ -1225,7 +1315,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
@@ -1235,8 +1327,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const clearFavicon =
|
||||
confirmedNavigation &&
|
||||
current.favicon !== undefined &&
|
||||
safeHttpOrigin(current.favicon.pageUrl) !==
|
||||
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
...(clearFavicon ? currentWithoutFavicon : current),
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
@@ -1250,10 +1348,109 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const syncNavigation = () => runFork(syncState(false, true));
|
||||
const syncInPageNavigation = () => runFork(syncState(false));
|
||||
const navigationStarted = (
|
||||
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
|
||||
) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
|
||||
};
|
||||
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
|
||||
readonly captureDocumentId: number;
|
||||
readonly dataUrl: string;
|
||||
readonly pageUrl: string;
|
||||
readonly requestId: number;
|
||||
}) {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
|
||||
if (
|
||||
!pageOrigin ||
|
||||
wc.isDestroyed() ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
managed?.attachmentId !== attachmentId ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId ||
|
||||
safeHttpOrigin(wc.getURL()) !== pageOrigin
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const capturedAt = yield* currentMillis;
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (
|
||||
!current ||
|
||||
current.webContentsId !== wc.id ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId
|
||||
) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
|
||||
const pageUrl = wc.getURL();
|
||||
if (!safeHttpOrigin(pageUrl)) return;
|
||||
const candidates = selectFaviconCandidates(rawCandidates);
|
||||
if (candidates.length === 0) return;
|
||||
const eventKey = JSON.stringify([pageUrl, ...candidates]);
|
||||
if (activeCapture?.eventKey === eventKey) return;
|
||||
activeCapture?.controller.abort();
|
||||
const captureDocumentId = documentId;
|
||||
const requestId = ++nextRequestId;
|
||||
const controller = new AbortController();
|
||||
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
|
||||
runFork(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
|
||||
catch: (cause) =>
|
||||
new PreviewOperationError({
|
||||
operation: "captureFavicon",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.kind === "captured"
|
||||
? publishFavicon({
|
||||
captureDocumentId,
|
||||
dataUrl: result.dataUrl,
|
||||
pageUrl,
|
||||
requestId,
|
||||
})
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
controller.signal.aborted
|
||||
? Effect.void
|
||||
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (activeCapture?.requestId === requestId) activeCapture = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
@@ -1316,14 +1513,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
});
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
if (isPreviewRefreshShortcut(input)) {
|
||||
event.preventDefault();
|
||||
runFork(
|
||||
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
|
||||
wc.reload(),
|
||||
).pipe(Effect.ignore),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runFork(forwardShortcut(event, input));
|
||||
};
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
cancelFaviconCapture();
|
||||
wc.off("did-start-navigation", navigationStarted);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("page-favicon-updated", faviconUpdated as never);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
wc.off("did-fail-load", failed as never);
|
||||
@@ -1333,9 +1542,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-start-navigation", navigationStarted);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("page-favicon-updated", faviconUpdated as never);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
wc.on("did-fail-load", failed as never);
|
||||
@@ -1352,7 +1563,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* Ref.update(attachedRef, (attached) =>
|
||||
replaceMap(attached, (copy) => {
|
||||
copy.set(wc.id, { scope });
|
||||
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1495,6 +1706,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
if (
|
||||
!wc ||
|
||||
wc.isDestroyed() ||
|
||||
wc.getType() !== "webview" ||
|
||||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
|
||||
) {
|
||||
@@ -1502,7 +1714,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const currentAttachment = attached.get(webContentsId);
|
||||
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
@@ -1514,7 +1727,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
tab.webContentsId != null &&
|
||||
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
|
||||
? tab.webContentsId
|
||||
: null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
@@ -1561,8 +1777,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = {
|
||||
...current,
|
||||
...currentWithoutFavicon,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
@@ -1641,6 +1858,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
pictureInPicture: current?.pictureInPicture ?? false,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
...(current?.favicon ? { favicon: current.favicon } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
@@ -1652,17 +1870,48 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
const webContentsId = pending.webContentsId;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) {
|
||||
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
yield* withTabLifecycleLock(
|
||||
tabId,
|
||||
Effect.gen(function* () {
|
||||
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
const currentWebContents = webContents.fromId(webContentsId);
|
||||
if (
|
||||
currentTab?.webContentsId !== webContentsId ||
|
||||
currentAttachment !== expectedAttachment ||
|
||||
(currentWebContents && !currentWebContents.isDestroyed())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(webContentsId),
|
||||
detachListeners(webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (current?.webContentsId !== webContentsId) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
|
||||
return [
|
||||
Option.some(next),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
@@ -1743,7 +1992,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* cancelPickElement(tabId);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
|
||||
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
|
||||
(resume) => {
|
||||
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
|
||||
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
|
||||
@@ -1758,14 +2007,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
|
||||
payload: PreviewAnnotationPayload | null,
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
|
||||
if (!active || active.cancel !== cancel) return;
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
});
|
||||
const settle = (payload: PreviewAnnotationPayload | null) => {
|
||||
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
|
||||
runFork(settlePick(payload));
|
||||
};
|
||||
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
|
||||
@@ -1795,11 +2044,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const cropRect = normalizeCaptureRect(args[1]);
|
||||
const submission = args[2] === "send" ? "send" : "attach";
|
||||
runFork(
|
||||
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: () => Effect.sync(() => settle(payload)),
|
||||
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
|
||||
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
|
||||
onSuccess: (screenshot) =>
|
||||
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
|
||||
}),
|
||||
Effect.ensuring(
|
||||
attempt(
|
||||
@@ -3537,7 +3788,7 @@ export class PreviewManager extends Context.Service<
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
|
||||
@@ -11,8 +11,10 @@ import type {
|
||||
PreviewAnnotationRegionTarget,
|
||||
PreviewAnnotationStrokeTarget,
|
||||
PreviewAnnotationStyleChange,
|
||||
PreviewAnnotationSubmission,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
@@ -426,7 +428,7 @@ function startAnnotation(): void {
|
||||
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
|
||||
composerRow.appendChild(dragHandle);
|
||||
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot");
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
|
||||
submit.className +=
|
||||
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
|
||||
composerRow.appendChild(submit);
|
||||
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
|
||||
refreshToolButtons();
|
||||
};
|
||||
|
||||
submit.addEventListener("click", () => {
|
||||
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
|
||||
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
|
||||
return;
|
||||
pendingCapture = true;
|
||||
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
|
||||
...regions.map((region) => region.rect),
|
||||
...strokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
});
|
||||
});
|
||||
comment.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
|
||||
};
|
||||
submit.addEventListener("click", () => submitAnnotation("attach"));
|
||||
root.addEventListener("keydown", (event) => {
|
||||
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
|
||||
// Keep this in the bubble phase so editor inputs receive the event before
|
||||
// it is isolated from listeners installed by the inspected page.
|
||||
event.stopImmediatePropagation();
|
||||
if (!submission) return;
|
||||
event.preventDefault();
|
||||
submit.click();
|
||||
submitAnnotation(submission);
|
||||
});
|
||||
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
|
||||
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(
|
||||
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
|
||||
),
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"normalizes unsupported linux password-store values without dropping other settings",
|
||||
() =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
environment.desktopSettingsPath,
|
||||
`{
|
||||
"linuxPasswordStore": "unsupported-store",
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"updateChannel": "nightly",
|
||||
"updateChannelConfiguredByUser": true
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
|
||||
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly linuxPasswordStore: LinuxPasswordStorePreference;
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
|
||||
document.linuxPasswordStore = settings.linuxPasswordStore;
|
||||
}
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
|
||||
@@ -13,16 +13,26 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
fontFamilyCode: "",
|
||||
fontFamilyComposer: "",
|
||||
fontFamilySans: "",
|
||||
fontFamilyTerminal: "",
|
||||
fontSizeCode: 13,
|
||||
fontSizeInterface: 16,
|
||||
fontSizePrompt: 14,
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarAutoSettleOnMerge: true,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -30,8 +40,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
legacySidebarEnabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopShellEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -230,6 +231,7 @@ describe("DesktopShellEnvironment", () => {
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.local\\bin",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
@@ -243,6 +245,65 @@ describe("DesktopShellEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "wrong-launcher",
|
||||
XDG_SESSION_DESKTOP: "wrong-launcher",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "KDE",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
XDG_SESSION_TYPE: "wayland",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_TYPE, "wayland");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("overrides stale dbus session addresses from the login shell", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
|
||||
}),
|
||||
);
|
||||
|
||||
it("resolves dbus runtime dir candidates with existence checks", () => {
|
||||
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
|
||||
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
|
||||
uid: 1000,
|
||||
exists: (path) => path === "/run/user/1000/bus",
|
||||
});
|
||||
|
||||
assert.equal(busPath, "unix:path=/run/user/1000/bus");
|
||||
});
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DISPLAY",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const;
|
||||
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
|
||||
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
|
||||
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
|
||||
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
|
||||
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
|
||||
|
||||
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
|
||||
|
||||
const linuxRuntimeDirCandidates = (
|
||||
env: NodeJS.ProcessEnv,
|
||||
uid: number | undefined,
|
||||
): ReadonlyArray<string> => {
|
||||
const candidates: string[] = [];
|
||||
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
|
||||
if (Option.isSome(fromEnv)) {
|
||||
candidates.push(normalizeRuntimeDir(fromEnv.value));
|
||||
}
|
||||
if (uid !== undefined) {
|
||||
candidates.push(`/run/user/${uid}`);
|
||||
}
|
||||
return candidates.filter((candidate) => candidate.length > 0);
|
||||
};
|
||||
|
||||
function resolveDefaultLinuxDbusSessionBusPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly uid: number | undefined;
|
||||
readonly exists?: (path: string) => boolean;
|
||||
}): string | null {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
|
||||
const busPath = `${runtimeDir}/bus`;
|
||||
if (input.exists === undefined || input.exists(busPath)) {
|
||||
return busPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly exists: (path: string) => boolean;
|
||||
readonly uid: number | undefined;
|
||||
}): string | null {
|
||||
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
|
||||
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
|
||||
}
|
||||
|
||||
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
|
||||
const normalized = entry.trim().replace(/^"+|"+$/g, "");
|
||||
return platform === "win32" ? normalized.toLowerCase() : normalized;
|
||||
@@ -158,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
|
||||
...trimNonEmpty(env.USERPROFILE).pipe(
|
||||
Option.match({
|
||||
onNone: () => [],
|
||||
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -330,10 +379,18 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
|
||||
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
|
||||
loadProfile: true,
|
||||
});
|
||||
// Concurrent, not sequential: these two probes are independent (only their
|
||||
// results are combined below) and each spawns its own PowerShell. Run in
|
||||
// series they sit at offset 0 of desktop.startup, before anything else, and
|
||||
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
|
||||
// startup span, of which desktop.bootstrap is ~30ms.
|
||||
const [noProfile, profile] = yield* Effect.all(
|
||||
[
|
||||
readWindowsEnvironment(["PATH"], { loadProfile: false }),
|
||||
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
const mergedPath = mergePaths("win32", [
|
||||
trimNonEmpty(profile.PATH),
|
||||
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
|
||||
@@ -356,7 +413,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const shellEnvironment: EnvironmentPatch = {};
|
||||
|
||||
for (const shell of listLoginShellCandidates(config)) {
|
||||
@@ -383,23 +445,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
|
||||
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
const shellPreferredEnvNames = [
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
] as const;
|
||||
for (const name of shellPreferredEnvNames) {
|
||||
if (shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
for (const name of [
|
||||
"DISPLAY",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const) {
|
||||
if (!config.env[name] && shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
config.platform === "linux" &&
|
||||
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
|
||||
) {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
|
||||
const dbusSessionBusPath = `${runtimeDir}/bus`;
|
||||
const busExists = yield* fileSystem
|
||||
.exists(dbusSessionBusPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (busExists) {
|
||||
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const installShellEnvironment = (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
|
||||
if (config.platform === "win32") {
|
||||
return installWindowsEnvironment(config);
|
||||
}
|
||||
@@ -411,6 +504,7 @@ const installShellEnvironment = (
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
|
||||
installShellEnvironment({
|
||||
@@ -418,6 +512,7 @@ export const make = Effect.gen(function* () {
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("stops when its scope closes during an Electron telemetry sample", () =>
|
||||
Effect.gen(function* () {
|
||||
const pollStarted = yield* Deferred.make<void>();
|
||||
const blockPoll = yield* Deferred.make<void>();
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(blockPoll)),
|
||||
Effect.as(0),
|
||||
),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: () => Effect.void,
|
||||
onThermalStateChange: () => Effect.void,
|
||||
onSpeedLimitChange: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
|
||||
yield* Layer.buildWithScope(layer, scope);
|
||||
yield* Deferred.await(pollStarted);
|
||||
|
||||
const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.isDefined(closeFiber.pollUnsafe());
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
const systemIdleState = yield* Ref.make<ElectronPowerMonitor.ElectronIdleState>("active");
|
||||
let beforeSystemIdleState: Effect.Effect<void> = Effect.void;
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000.75,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () =>
|
||||
beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const messages = yield* Effect.forEach(encoded, (bytes) =>
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
}
|
||||
assert.deepEqual(initialSnapshot.electronProcesses, []);
|
||||
assert.equal(initialSnapshot.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.creationTimeMs, 1_001);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
yield* publisher.handleControlForSource("secondary-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
yield* publisher.handleControlForSource("old-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* publisher.handleControlForSource("secondary-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
yield* Effect.all(
|
||||
[
|
||||
publisher.removeControlSource("old-backend"),
|
||||
publisher.handleControlForSource("replacement-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
}),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
yield* Ref.set(onBattery, true);
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true");
|
||||
|
||||
yield* Ref.set(onBattery, false);
|
||||
const metricsBeforePolledAc = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.seconds(5));
|
||||
assert.equal(metricsReadCount, metricsBeforePolledAc + 1);
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false");
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(metricsReadCount, metricsBeforePolledAc + 2);
|
||||
|
||||
const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
simpleListeners.get("suspend")?.();
|
||||
const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber));
|
||||
assert.isTrue(suspendedSnapshot.power.suspended);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
assert.isTrue(constrainedSnapshot.power.suspended);
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber));
|
||||
assert.isFalse(recoveredSnapshot.power.suspended);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim());
|
||||
if (decodedSpeedLimit.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the encoded telemetry message to be a snapshot.");
|
||||
}
|
||||
assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65);
|
||||
assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001);
|
||||
|
||||
const metricsBeforeSecondaryOnlySample = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1);
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid,
|
||||
4_242,
|
||||
);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("replacement-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setHostPowerIntervals",
|
||||
activeIntervalMs: 7_000,
|
||||
idleIntervalMs: 11_000,
|
||||
});
|
||||
const configuredSequence = Option.getOrThrow(
|
||||
yield* Fiber.join(configuredSnapshotFiber),
|
||||
).sequence;
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(6_999));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
configuredSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
configuredSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
|
||||
yield* Ref.set(systemIdleState, "locked");
|
||||
yield* TestClock.adjust(Duration.seconds(7));
|
||||
const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence;
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true");
|
||||
yield* TestClock.adjust(Duration.millis(10_999));
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
lockedSequence + 1,
|
||||
);
|
||||
|
||||
yield* Ref.set(systemIdleState, "active");
|
||||
yield* TestClock.adjust(Duration.seconds(11));
|
||||
const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow);
|
||||
assert.equal(unlockedSnapshot.power.locked, "false");
|
||||
assert.equal(unlockedSnapshot.power.idle, "false");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(6_999));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
unlockedSnapshot.sequence,
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
unlockedSnapshot.sequence + 1,
|
||||
);
|
||||
|
||||
const pollStarted = yield* Deferred.make<void>();
|
||||
const releasePoll = yield* Deferred.make<void>();
|
||||
beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releasePoll)),
|
||||
);
|
||||
const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* Deferred.await(pollStarted);
|
||||
simpleListeners.get("lock-screen")?.();
|
||||
thermalListener?.("critical");
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Deferred.succeed(releasePoll, undefined);
|
||||
|
||||
const concurrentEventSnapshot = Option.getOrThrow(
|
||||
yield* Fiber.join(concurrentEventSnapshotFiber),
|
||||
);
|
||||
assert.equal(concurrentEventSnapshot.power.locked, "true");
|
||||
assert.equal(concurrentEventSnapshot.power.thermalState, "critical");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
|
||||
const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly idle: HostPowerSnapshot["idle"];
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly lockedEventPending: boolean;
|
||||
readonly suspended: boolean;
|
||||
readonly suspendedEventPending: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly onBatteryEventPending: boolean;
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
interface HostPowerIntervals {
|
||||
readonly active: Duration.Duration;
|
||||
readonly idle: Duration.Duration;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
{
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
readonly handleControlForSource: (
|
||||
sourceId: string,
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return {
|
||||
...state,
|
||||
locked: booleanState(event.value),
|
||||
lockedEventPending: true,
|
||||
};
|
||||
case "suspended":
|
||||
return {
|
||||
...state,
|
||||
suspended: event.value,
|
||||
suspendedEventPending: event.value,
|
||||
};
|
||||
case "onBattery":
|
||||
return {
|
||||
...state,
|
||||
onBattery: booleanState(event.value),
|
||||
onBatteryEventPending: true,
|
||||
};
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(
|
||||
power: PowerState,
|
||||
diagnosticsDemand: boolean,
|
||||
hostPowerIntervals: HostPowerIntervals,
|
||||
): Duration.Duration {
|
||||
if (!diagnosticsDemand) {
|
||||
return power.suspended || power.locked === "true" || power.idle === "true"
|
||||
? hostPowerIntervals.idle
|
||||
: hostPowerIntervals.active;
|
||||
}
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
idle: "unknown",
|
||||
locked: "unknown",
|
||||
lockedEventPending: false,
|
||||
suspended: false,
|
||||
suspendedEventPending: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
onBatteryEventPending: false,
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
|
||||
active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
|
||||
idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
|
||||
});
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = (allowSuspendRecovery: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const polledLocked =
|
||||
systemIdleState === "unknown"
|
||||
? currentPower.locked
|
||||
: booleanState(systemIdleState === "locked");
|
||||
const polledOnBattery = booleanState(onBattery);
|
||||
const observedPower = yield* Ref.modify(powerState, (latestPower) => {
|
||||
const preserveEventLocked =
|
||||
latestPower.lockedEventPending ||
|
||||
latestPower.locked !== currentPower.locked ||
|
||||
latestPower.lockedEventPending !== currentPower.lockedEventPending;
|
||||
const preserveEventOnBattery =
|
||||
latestPower.onBatteryEventPending ||
|
||||
latestPower.onBattery !== currentPower.onBattery ||
|
||||
latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
|
||||
const preserveEventSuspended =
|
||||
latestPower.suspendedEventPending ||
|
||||
latestPower.suspended !== currentPower.suspended ||
|
||||
latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
|
||||
const next: PowerState = {
|
||||
...latestPower,
|
||||
idle: idleState(systemIdleState),
|
||||
locked: preserveEventLocked ? latestPower.locked : polledLocked,
|
||||
lockedEventPending:
|
||||
latestPower.lockedEventPending &&
|
||||
(systemIdleState === "unknown" || polledLocked !== latestPower.locked),
|
||||
suspended:
|
||||
allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
|
||||
suspendedEventPending: false,
|
||||
onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
|
||||
onBatteryEventPending:
|
||||
latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
|
||||
};
|
||||
return [next, next] as const;
|
||||
});
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: observedPower.idle,
|
||||
idleSeconds,
|
||||
locked: observedPower.locked,
|
||||
suspended: observedPower.suspended,
|
||||
onBattery: observedPower.onBattery,
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: observedPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: observedPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce(false);
|
||||
while (true) {
|
||||
const [currentPower, demand, intervals] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
|
||||
Ref.get(hostPowerIntervals),
|
||||
]);
|
||||
const allowSuspendRecovery = yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers).pipe(Effect.as(false)),
|
||||
Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
|
||||
);
|
||||
yield* sampleOnce(allowSuspendRecovery);
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
|
||||
sourceId,
|
||||
message,
|
||||
) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.modify(diagnosticsDemandSources, (sources) => {
|
||||
const previous = sources.size > 0;
|
||||
const next = new Set(sources);
|
||||
if (message.enabled) {
|
||||
next.add(sourceId);
|
||||
} else {
|
||||
next.delete(sourceId);
|
||||
}
|
||||
return [[previous, next.size > 0] as const, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(([previous, enabled]) =>
|
||||
previous === enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
case "setHostPowerIntervals":
|
||||
return Ref.set(hostPowerIntervals, {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
sourceId,
|
||||
) =>
|
||||
Ref.modify(diagnosticsDemandSources, (sources) => {
|
||||
const previous = sources.size > 0;
|
||||
const next = new Set(sources);
|
||||
next.delete(sourceId);
|
||||
return [[previous, next.size > 0] as const, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(([previous, enabled]) =>
|
||||
previous === enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
|
||||
handleControlForSource("legacy", message);
|
||||
|
||||
const snapshots = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(changes);
|
||||
const initial = yield* Ref.get(latest);
|
||||
return Stream.concat(
|
||||
Option.match(initial, {
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
Stream.fromSubscription(subscription),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -39,19 +39,20 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
confirm: () => Effect.succeed(false),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
} satisfies ElectronDialog.ElectronDialog["Service"]);
|
||||
@@ -79,6 +80,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
zoomMain: (direction) =>
|
||||
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
@@ -92,6 +95,30 @@ const makeElectronMenuLayer = (
|
||||
showContextMenu: () => Effect.succeed(Option.none()),
|
||||
} satisfies ElectronMenu.ElectronMenu["Service"]);
|
||||
|
||||
const configureMenu = (
|
||||
selectedAction: Deferred.Deferred<string>,
|
||||
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
yield* menu.configure;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopApplicationMenu.layer.pipe(
|
||||
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
|
||||
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
|
||||
Layer.provideMerge(desktopUpdatesLayer),
|
||||
Layer.provideMerge(electronDialogLayer),
|
||||
Layer.provideMerge(electronAppLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopApplicationMenu", () => {
|
||||
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -99,25 +126,7 @@ describe("DesktopApplicationMenu", () => {
|
||||
const applicationMenuTemplate =
|
||||
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
yield* menu.configure;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopApplicationMenu.layer.pipe(
|
||||
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
|
||||
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
|
||||
Layer.provideMerge(desktopUpdatesLayer),
|
||||
Layer.provideMerge(electronDialogLayer),
|
||||
Layer.provideMerge(electronAppLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* configureMenu(selectedAction, applicationMenuTemplate);
|
||||
|
||||
const template = yield* Deferred.await(applicationMenuTemplate);
|
||||
const fileMenu = template.find((item) => item.label === "File");
|
||||
@@ -136,4 +145,38 @@ describe("DesktopApplicationMenu", () => {
|
||||
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
|
||||
}),
|
||||
);
|
||||
|
||||
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
|
||||
// zoom roles: the roles zoom whichever webContents has focus, which breaks
|
||||
// app zoom while an embedded preview WebContentsView holds focus.
|
||||
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
|
||||
Effect.gen(function* () {
|
||||
const selectedAction = yield* Deferred.make<string>();
|
||||
const applicationMenuTemplate =
|
||||
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
|
||||
|
||||
yield* configureMenu(selectedAction, applicationMenuTemplate);
|
||||
|
||||
const template = yield* Deferred.await(applicationMenuTemplate);
|
||||
const viewMenu = template.find((item) => item.label === "View");
|
||||
assert.isDefined(viewMenu);
|
||||
if (!Array.isArray(viewMenu.submenu)) {
|
||||
throw new Error("Expected View menu submenu to be an array.");
|
||||
}
|
||||
|
||||
assert.isUndefined(
|
||||
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
|
||||
);
|
||||
|
||||
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
|
||||
assert.isDefined(zoomIn);
|
||||
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
|
||||
if (typeof zoomIn.click !== "function") {
|
||||
throw new Error("Expected Zoom In menu item to have a click handler.");
|
||||
}
|
||||
|
||||
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
|
||||
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
|
||||
yield* desktopWindow.dispatchMenuAction(action);
|
||||
});
|
||||
|
||||
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
|
||||
direction: DesktopWindow.MainWindowZoomDirection,
|
||||
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.zoomMain(direction);
|
||||
});
|
||||
|
||||
const checkForUpdatesFromMenu = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -127,6 +134,9 @@ export const make = Effect.gen(function* () {
|
||||
const settingsClick = () => {
|
||||
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
|
||||
};
|
||||
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
|
||||
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
|
||||
};
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
|
||||
{ role: "forceReload" },
|
||||
{ role: "toggleDevTools" },
|
||||
{ type: "separator" },
|
||||
{ role: "resetZoom" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
|
||||
{ role: "zoomOut" },
|
||||
/*
|
||||
Not the zoom roles: those act on the focused webContents, so with
|
||||
an embedded preview WebContentsView focused they zoom the guest
|
||||
page and the app UI appears stuck. These always zoom the main
|
||||
window (see DesktopWindow.zoomMain).
|
||||
*/
|
||||
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
|
||||
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
|
||||
{
|
||||
label: "Zoom In",
|
||||
accelerator: "CmdOrCtrl+Plus",
|
||||
visible: false,
|
||||
click: zoomClick("in"),
|
||||
},
|
||||
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
|
||||
{ type: "separator" },
|
||||
{ role: "togglefullscreen" },
|
||||
],
|
||||
|
||||
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
|
||||
if (!beforeInput) {
|
||||
return yield* Effect.die("before-input-event listener was not registered");
|
||||
}
|
||||
|
||||
let prevented = false;
|
||||
const event = { preventDefault: () => (prevented = true) };
|
||||
const input = {
|
||||
type: "keyDown",
|
||||
isAutoRepeat: true,
|
||||
key: "W",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
};
|
||||
beforeInput(event, input);
|
||||
assert.isTrue(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, isAutoRepeat: false });
|
||||
assert.isFalse(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, meta: false });
|
||||
assert.isFalse(prevented);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
|
||||
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
|
||||
// that dies on boot cannot reload-loop forever.
|
||||
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
|
||||
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
|
||||
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
@@ -54,6 +61,8 @@ export type DesktopWindowError =
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export type MainWindowZoomDirection = "in" | "out" | "reset";
|
||||
|
||||
export class DesktopWindow extends Context.Service<
|
||||
DesktopWindow,
|
||||
{
|
||||
@@ -80,6 +89,12 @@ export class DesktopWindow extends Context.Service<
|
||||
readonly handleBackendNotReady: Effect.Effect<void>;
|
||||
readonly flushMainWindowBounds: Effect.Effect<void>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
// Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
|
||||
// menu roles act on whichever webContents has keyboard focus, so with an
|
||||
// embedded preview WebContentsView (or DevTools) focused they zoom the
|
||||
// guest page instead of the app UI. The menu routes here to always target
|
||||
// the main window.
|
||||
readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/window/DesktopWindow") {}
|
||||
@@ -514,6 +529,18 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
@@ -537,6 +564,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let rendererRecoveryTimestamps: number[] = [];
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
@@ -618,10 +646,39 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
window.webContents.on("render-process-gone", (_event, details) => {
|
||||
void runPromise(
|
||||
logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
const recoverable =
|
||||
details.reason === "crashed" ||
|
||||
details.reason === "oom" ||
|
||||
details.reason === "abnormal-exit";
|
||||
// Long sessions can OOM the renderer (V8 heap exhaustion from
|
||||
// accumulated thread state). Without a reload the user is left staring
|
||||
// at a dead white window while agents keep running invisibly, so
|
||||
// recover by reloading — the renderer rehydrates from the backend,
|
||||
// which is unaffected. Recovery attempts are bounded so a renderer
|
||||
// that dies immediately on boot cannot reload-loop forever.
|
||||
runFork(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
|
||||
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
|
||||
);
|
||||
const shouldRecover =
|
||||
recoverable &&
|
||||
!window.isDestroyed() &&
|
||||
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
|
||||
yield* logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
recovering: shouldRecover,
|
||||
});
|
||||
if (!shouldRecover) {
|
||||
return;
|
||||
}
|
||||
rendererRecoveryTimestamps.push(now);
|
||||
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -787,6 +844,18 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
send();
|
||||
}),
|
||||
zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
|
||||
yield* Effect.annotateCurrentSpan({ direction });
|
||||
const window = yield* focusedMainWindow;
|
||||
if (Option.isNone(window) || window.value.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
const webContents = window.value.webContents;
|
||||
// Same step size as the Electron zoomIn/zoomOut menu roles.
|
||||
webContents.setZoomLevel(
|
||||
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
|
||||
);
|
||||
}),
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
yield* electronWindow.syncAllAppearance((window) =>
|
||||
|
||||
@@ -229,15 +229,18 @@ const NODE_PTY_PROBE_SCRIPT = (
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
// can't read inside app.asar, so confirm those deps are unpacked on the real
|
||||
// filesystem before reporting the backend healthy. "effect" is the framework
|
||||
// every server module imports; resolving it validates the whole node_modules
|
||||
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
|
||||
// report it accurately instead of letting the server crash on
|
||||
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
|
||||
// launch with no fallback).
|
||||
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
|
||||
// The WSL Node can't read inside app.asar, so confirm what the server needs is
|
||||
// unpacked on the real filesystem before reporting the backend healthy. Exit 3
|
||||
// marks this distinct from a node-pty prebuild problem so the caller can report
|
||||
// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
|
||||
// launch (which, in wsl-only mode, would just fail to launch with no fallback).
|
||||
//
|
||||
// The sentinel must be a package the CLI bundle leaves external. It used to be
|
||||
// "effect", back when the bundle externalized its runtime deps and the whole
|
||||
// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
|
||||
// so "effect" no longer exists on disk and only the native packages do —
|
||||
// resolving node-pty is what actually validates the unpacked tree.
|
||||
try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
@@ -462,16 +465,17 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
|
||||
// filesystem — a packaging regression, since the server bundle needs its
|
||||
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
|
||||
// Windows and dual mode surfaces the reason inline, instead of the server
|
||||
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
|
||||
// The packages the server bundle leaves external (node-pty and the other
|
||||
// native addons) couldn't be resolved on the WSL filesystem — a packaging
|
||||
// regression, since those must be unpacked from the asar. Fatal so wsl-only
|
||||
// mode falls back to Windows and dual mode surfaces the reason inline,
|
||||
// instead of the server crash-looping on ERR_MODULE_NOT_FOUND once it
|
||||
// actually launches.
|
||||
if (probe.exitCode === 3) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
|
||||
'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
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 Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "./DesktopWslServerTree.ts";
|
||||
|
||||
// The service reads packaged Windows roots through the (asar-aware, in
|
||||
// Electron) fs, so a plain directory named server.asar exercises the full
|
||||
// extraction path under plain Node.
|
||||
|
||||
const environmentLayer = (input: {
|
||||
readonly baseDir: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly appVersion?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
}) =>
|
||||
DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: input.baseDir,
|
||||
platform: "win32",
|
||||
processArch: "x64",
|
||||
appVersion: input.appVersion ?? "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: input.isPackaged ?? true,
|
||||
resourcesPath: input.resourcesPath,
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: input.baseDir,
|
||||
T3CODE_MODE: "desktop",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const withTempDir = <A, E, R>(
|
||||
run: (tempDir: string) => Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<
|
||||
A,
|
||||
E | PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Exclude<R, Scope.Scope>
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-wsl-server-tree-test-",
|
||||
});
|
||||
return yield* run(tempDir);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const ensureWith = (input: {
|
||||
readonly baseDir: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly appVersion?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
return yield* tree.ensure;
|
||||
}).pipe(
|
||||
Effect.provide(DesktopWslServerTree.layer.pipe(Layer.provideMerge(environmentLayer(input)))),
|
||||
);
|
||||
|
||||
describe("DesktopWslServerTree", () => {
|
||||
it.effect("bounds entry work across an eight-way nested tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const active = yield* Ref.make(0);
|
||||
const maxActive = yield* Ref.make(0);
|
||||
const visited = yield* Ref.make(0);
|
||||
|
||||
yield* DesktopWslServerTree.forEachBoundedTree([{ depth: 0, id: "root" }], (node) =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.updateAndGet(active, (count) => count + 1);
|
||||
yield* Ref.update(maxActive, (maximum) => Math.max(maximum, current));
|
||||
yield* Ref.update(visited, (count) => count + 1);
|
||||
}),
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
// Give every task in the current batch a chance to overlap.
|
||||
yield* Effect.yieldNow;
|
||||
if (node.depth === 4) return [];
|
||||
return Array.from({ length: 8 }, (_, index) => ({
|
||||
depth: node.depth + 1,
|
||||
id: `${node.id}.${String(index)}`,
|
||||
}));
|
||||
}),
|
||||
() => Ref.update(active, (count) => count - 1),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(yield* Ref.get(active), 0);
|
||||
assert.equal(yield* Ref.get(maxActive), 8);
|
||||
assert.equal(yield* Ref.get(visited), 4_681);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the server root unchanged when it is a plain directory (dev)", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: tempDir,
|
||||
isPackaged: false,
|
||||
});
|
||||
assert.isTrue(result.ok);
|
||||
assert.isFalse(result.ok && result.root.endsWith(".asar"));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("extracts an archive root into a version-keyed state directory", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"server-entry",
|
||||
);
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "node_modules/effect"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "node_modules/effect/package.json"),
|
||||
"{}",
|
||||
);
|
||||
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
|
||||
assert.isTrue(result.ok);
|
||||
const root = result.ok ? result.root : "";
|
||||
assert.include(root, path.join("wsl-server-tree", "1.2.3"));
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "server-entry");
|
||||
const dep = yield* fileSystem.exists(path.join(root, "node_modules/effect/package.json"));
|
||||
assert.isTrue(dep);
|
||||
const marker = yield* fileSystem.readFileString(
|
||||
path.join(root, "t3code-wsl-server-tree.json"),
|
||||
);
|
||||
assert.include(marker, '"version":"1.2.3"');
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent extraction callers and publishes one complete tree", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const resourcesPath = path.join(tempDir, "resources");
|
||||
const serverRoot = path.join(resourcesPath, "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"server-entry",
|
||||
);
|
||||
|
||||
const results = yield* Effect.gen(function* () {
|
||||
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
return yield* Effect.all([tree.ensure, tree.ensure], { concurrency: "unbounded" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslServerTree.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(results.every((result) => result.ok));
|
||||
const roots = results.flatMap((result) => (result.ok ? [result.root] : []));
|
||||
assert.lengthOf(new Set(roots), 1);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(path.join(roots[0] ?? "", "apps/server/dist/bin.mjs")),
|
||||
"server-entry",
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reuses a completed extraction instead of copying again", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "v1");
|
||||
|
||||
const first = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(first.ok);
|
||||
|
||||
// Mutate the source; a reused tree must keep the first copy.
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"v2-should-not-appear",
|
||||
);
|
||||
const second = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(second.ok);
|
||||
const root = second.ok ? second.root : "";
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "v1");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("sweeps stale version directories and leftover partials after extraction", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "x");
|
||||
|
||||
// T3CODE_HOME is set to tempDir, so the desktop state dir resolves to
|
||||
// <tempDir>/userdata (no .t3 segment).
|
||||
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
|
||||
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.0.0"), { recursive: true });
|
||||
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.2.3.partial"), { recursive: true });
|
||||
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(result.ok);
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.0.0")));
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3.partial")));
|
||||
assert.isTrue(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("re-extracts when the app version changes", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "old");
|
||||
|
||||
const first = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
appVersion: "1.2.3",
|
||||
});
|
||||
assert.isTrue(first.ok);
|
||||
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "new");
|
||||
const second = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
appVersion: "1.2.4",
|
||||
});
|
||||
assert.isTrue(second.ok);
|
||||
const root = second.ok ? second.root : "";
|
||||
assert.include(root, "1.2.4");
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "new");
|
||||
// The previous version's tree is gone.
|
||||
const treeRoot = path.dirname(root);
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a retryable failure when the archive cannot be read", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
// resources dir exists but server.asar does not
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isFalse(result.ok);
|
||||
if (!result.ok) {
|
||||
assert.include(result.reason, "could not be extracted");
|
||||
assert.isFalse(result.fatal);
|
||||
}
|
||||
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
|
||||
const leftovers = yield* fileSystem
|
||||
.readDirectory(treeRoot)
|
||||
.pipe(Effect.orElseSucceed(() => []));
|
||||
assert.deepStrictEqual(leftovers, []);
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
|
||||
// Packaged Windows builds ship the server tree inside resources/server.asar
|
||||
// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in
|
||||
// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL
|
||||
// backend launches plain `wsl.exe -- node`, which cannot read an asar
|
||||
// archive. This service materializes the archive into a real, version-keyed
|
||||
// directory the first time the WSL backend starts, and reuses it afterwards —
|
||||
// so only users who enable WSL ever pay for a loose copy of the server tree.
|
||||
//
|
||||
// Reading through Electron's patched fs also transparently returns the
|
||||
// contents of files that electron-builder/asar left in the server.asar.unpacked
|
||||
// sibling (native binaries), so a single walk of the archive yields the
|
||||
// complete tree.
|
||||
|
||||
export type WslServerTreeResult =
|
||||
| { readonly ok: true; readonly root: string }
|
||||
| { readonly ok: false; readonly reason: string; readonly fatal: boolean };
|
||||
|
||||
const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
|
||||
const COPY_CONCURRENCY = 8;
|
||||
|
||||
const Marker = Schema.Struct({ version: Schema.String });
|
||||
const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
|
||||
const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
|
||||
|
||||
export class DesktopWslServerTreeExtractError extends Schema.TaggedErrorClass<DesktopWslServerTreeExtractError>()(
|
||||
"DesktopWslServerTreeExtractError",
|
||||
{
|
||||
targetDir: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to extract the WSL server tree to ${this.targetDir}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopWslServerTree extends Context.Service<
|
||||
DesktopWslServerTree,
|
||||
{
|
||||
// Resolves the directory the WSL backend should treat as the app root
|
||||
// (the directory containing apps/server/dist and node_modules). In dev
|
||||
// the checkout already is that directory; packaged Windows builds extract
|
||||
// server.asar on first use.
|
||||
readonly ensure: Effect.Effect<WslServerTreeResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
|
||||
|
||||
// Child scheduling stays here instead of inside `visit`, so nested directories
|
||||
// cannot create independent concurrency pools. The LIFO work list also keeps
|
||||
// traversal memory proportional to the remaining frontier rather than the
|
||||
// number of active fibers.
|
||||
export const forEachBoundedTree = <Node, E, R>(
|
||||
roots: ReadonlyArray<Node>,
|
||||
visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
|
||||
): Effect.Effect<void, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const pending = [...roots];
|
||||
while (pending.length > 0) {
|
||||
const batch = pending.splice(-COPY_CONCURRENCY);
|
||||
const children = yield* Effect.forEach(batch, visit, {
|
||||
concurrency: COPY_CONCURRENCY,
|
||||
});
|
||||
for (const entries of children) {
|
||||
pending.push(...entries);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
interface CopyTreeEntry {
|
||||
readonly sourcePath: string;
|
||||
readonly targetPath: string;
|
||||
}
|
||||
|
||||
// Copy using only operations supported by Electron's asar-patched fs. Symlinks
|
||||
// are not expected because the sidecar is installed with a hoisted, physical
|
||||
// layout; anything that is neither a file nor a directory is skipped.
|
||||
const copyTree = (
|
||||
fs: FileSystem.FileSystem,
|
||||
join: (first: string, ...rest: string[]) => string,
|
||||
from: string,
|
||||
to: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError> =>
|
||||
forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
|
||||
[{ sourcePath: from, targetPath: to }],
|
||||
({ sourcePath, targetPath }) =>
|
||||
Effect.gen(function* () {
|
||||
const info = yield* fs.stat(sourcePath);
|
||||
if (info.type === "Directory") {
|
||||
yield* fs.makeDirectory(targetPath, { recursive: true });
|
||||
const entries = yield* fs.readDirectory(sourcePath);
|
||||
return entries.map((entry) => ({
|
||||
sourcePath: join(sourcePath, entry),
|
||||
targetPath: join(targetPath, entry),
|
||||
}));
|
||||
}
|
||||
if (info.type === "File") {
|
||||
// Read and write stay in the same bounded task, so at most eight file
|
||||
// buffers can be retained while their writes complete.
|
||||
const bytes = yield* fs.readFile(sourcePath);
|
||||
yield* fs.writeFile(targetPath, bytes);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const join = environment.path.join;
|
||||
|
||||
const serverRoot = environment.serverRoot;
|
||||
const needsExtraction = environment.isPackaged && environment.platform === "win32";
|
||||
const treeRoot = join(environment.stateDir, "wsl-server-tree");
|
||||
const version = environment.appVersion;
|
||||
const versionDir = join(treeRoot, version);
|
||||
|
||||
// Remove sibling trees left behind by previous app versions (and aborted
|
||||
// extractions). Best-effort: a locked file must not block the backend.
|
||||
const sweepStale = Effect.gen(function* () {
|
||||
const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
|
||||
yield* Effect.forEach(
|
||||
entries.filter((entry) => entry !== version),
|
||||
(entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const markerMatches = Effect.gen(function* () {
|
||||
const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
|
||||
const marker = yield* decodeMarker(raw);
|
||||
return marker.version === version;
|
||||
}).pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const extract = Effect.gen(function* () {
|
||||
yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
|
||||
yield* fs.makeDirectory(treeRoot, { recursive: true });
|
||||
// Keep the temporary tree beside the target so rename is atomic. Cleanup
|
||||
// is owned explicitly because a scoped temp-directory finalizer treats the
|
||||
// successful rename (and therefore missing original path) as an error.
|
||||
const partialDir = yield* fs.makeTempDirectory({
|
||||
directory: treeRoot,
|
||||
prefix: `.${version}.extract-`,
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* copyTree(fs, join, serverRoot, partialDir);
|
||||
const markerJson = yield* encodeMarker({ version });
|
||||
yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
|
||||
// The marker is written before the rename, so a directory named after
|
||||
// the version is complete by construction.
|
||||
yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
|
||||
yield* fs.rename(partialDir, versionDir);
|
||||
}).pipe(
|
||||
Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
|
||||
);
|
||||
yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
// Serialize concurrent ensure calls (backend restarts can overlap): the
|
||||
// first caller extracts, later callers see the marker and reuse the tree.
|
||||
const gate = yield* Semaphore.make(1);
|
||||
|
||||
const ensure: Effect.Effect<WslServerTreeResult> = gate
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
if (!needsExtraction) {
|
||||
return { ok: true, root: serverRoot } as const;
|
||||
}
|
||||
if (yield* markerMatches) {
|
||||
yield* sweepStale;
|
||||
return { ok: true, root: versionDir } as const;
|
||||
}
|
||||
const result = yield* extract.pipe(
|
||||
Effect.map(() => ({ ok: true, root: versionDir }) as const),
|
||||
// Retryable: transient antivirus locks and slow disks are the common
|
||||
// causes, and the backend manager already bounds preflight retries.
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
reason: `WSL server files could not be extracted to ${versionDir}: ${
|
||||
error.cause instanceof Error ? error.cause.message : String(error.cause)
|
||||
}`,
|
||||
fatal: false,
|
||||
} as const),
|
||||
),
|
||||
);
|
||||
if (result.ok) {
|
||||
yield* sweepStale;
|
||||
}
|
||||
return result;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
|
||||
|
||||
return DesktopWslServerTree.of({ ensure });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopWslServerTree, make);
|
||||
|
||||
export interface DesktopWslServerTreeTestStub {
|
||||
readonly result?: WslServerTreeResult;
|
||||
}
|
||||
|
||||
export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
|
||||
Layer.effect(
|
||||
DesktopWslServerTree,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return DesktopWslServerTree.of({
|
||||
ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,5 +1,10 @@
|
||||
---
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
@@ -69,6 +74,8 @@ const {
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
|
||||
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
|
||||
<a href="/terms-of-service">Terms</a>
|
||||
<a href="/privacy-policy">Privacy</a>
|
||||
<a href="/security-policy">Security</a>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const IOS_APP_STORE_URL =
|
||||
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
|
||||
|
||||
export const ANDROID_PLAY_STORE_URL =
|
||||
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "14k+",
|
||||
users: "100,000",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -57,10 +58,28 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Mobile -->
|
||||
<section class="platform-section">
|
||||
<div class="platform-header">
|
||||
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18.5h2"/></svg>
|
||||
<h2 class="platform-name">Mobile</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">
|
||||
<span class="card-arch">iPhone & iPad</span>
|
||||
<span class="card-format">App Store</span>
|
||||
</a>
|
||||
<a class="download-card" href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">
|
||||
<span class="card-arch">Android</span>
|
||||
<span class="card-format">Google Play</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
Looking for older versions? Check the
|
||||
Looking for older versions? Check the{" "}
|
||||
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
@@ -73,7 +92,8 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
|
||||
async function init() {
|
||||
const versionLabel = document.getElementById("version-label");
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
|
||||
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
import { tweets } from "../lib/tweets";
|
||||
|
||||
const desktopEndorsementRows = [
|
||||
@@ -66,6 +71,12 @@ const mobileEndorsementRows = [
|
||||
<span>Steal our code (legally)</span>
|
||||
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<p class="hero-mobile-line">
|
||||
Also on your phone:
|
||||
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="hero-preview">
|
||||
@@ -578,6 +589,28 @@ const mobileEndorsementRows = [
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.hero-mobile-line {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--fg-dim);
|
||||
font-size: 13px;
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
|
||||
.hero-mobile-line a {
|
||||
color: var(--fg-muted);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(161, 161, 170, 0.4);
|
||||
text-underline-offset: 3px;
|
||||
transition: color 0.18s ease, text-decoration-color 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-mobile-line a:hover {
|
||||
color: var(--fg);
|
||||
text-decoration-color: var(--fg);
|
||||
}
|
||||
|
||||
/* Download button icons (platform-aware) */
|
||||
.dl-icon {
|
||||
display: none;
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
version: "1.0.4",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -181,6 +181,9 @@ const config: ExpoConfig = {
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
// Multitasking-capable iPad apps cannot rotate programmatically, so the
|
||||
// showcase capture build requires full screen (see infoPlist below).
|
||||
requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1",
|
||||
bundleIdentifier: iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
@@ -197,6 +200,21 @@ const config: ExpoConfig = {
|
||||
NSLocalNetworkUsageDescription:
|
||||
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
|
||||
ITSAppUsesNonExemptEncryption: false,
|
||||
// The App Store screenshot harness rotates the iPad interface from
|
||||
// inside the app (CI denies osascript the Accessibility access that
|
||||
// Simulator menu scripting needs), and iPadOS ignores programmatic
|
||||
// orientation requests for multitasking-capable apps — so the capture
|
||||
// build opts out of multitasking and declares landscape support.
|
||||
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
|
||||
? {
|
||||
"UISupportedInterfaceOrientations~ipad": [
|
||||
"UIInterfaceOrientationPortrait",
|
||||
"UIInterfaceOrientationPortraitUpsideDown",
|
||||
"UIInterfaceOrientationLandscapeLeft",
|
||||
"UIInterfaceOrientationLandscapeRight",
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
android: {
|
||||
@@ -275,10 +293,12 @@ const config: ExpoConfig = {
|
||||
"expo-camera",
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
microphonePermission: false,
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
@@ -318,6 +338,7 @@ const config: ExpoConfig = {
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
"./plugins/withAndroidTabletOrientation.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
|
||||
+7
@@ -252,6 +252,9 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
val textLength = editor.text?.length ?: 0
|
||||
val safeStart = start.coerceIn(0, textLength)
|
||||
val safeEnd = end.coerceIn(0, textLength)
|
||||
// Re-applying an unchanged selection resets the keyboard's suggestion
|
||||
// state, so a no-op assignment must be skipped.
|
||||
if (editor.selectionStart == safeStart && editor.selectionEnd == safeEnd) return
|
||||
editor.setSelection(safeStart, safeEnd)
|
||||
}
|
||||
|
||||
@@ -281,6 +284,10 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
)
|
||||
|
||||
private fun emitSelectionChange(start: Int, end: Int) {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange(
|
||||
mapOf(
|
||||
"value" to editor.text.toString(),
|
||||
|
||||
@@ -141,7 +141,7 @@ private final class ComposerTextView: UITextView {
|
||||
replace(textRange, withText: "")
|
||||
}
|
||||
|
||||
private func loadImages(from providers: [NSItemProvider]) {
|
||||
func loadImages(from providers: [NSItemProvider]) {
|
||||
let group = DispatchGroup()
|
||||
let lock = NSLock()
|
||||
var images = [UIImage?](repeating: nil, count: providers.count)
|
||||
@@ -282,7 +282,7 @@ private final class ComposerTextView: UITextView {
|
||||
}
|
||||
}
|
||||
|
||||
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropDelegate {
|
||||
private let textView = ComposerTextView()
|
||||
private let placeholderLabel = UILabel()
|
||||
private var value = ""
|
||||
@@ -326,6 +326,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
|
||||
clipsToBounds = false
|
||||
textView.delegate = self
|
||||
textView.textDropDelegate = self
|
||||
textView.backgroundColor = .clear
|
||||
textView.textContainerInset = .zero
|
||||
textView.textContainer.lineFragmentPadding = 0
|
||||
@@ -488,6 +489,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
return
|
||||
}
|
||||
restoreBaseTypingAttributes()
|
||||
// UIKit moves the selection before textViewDidChange runs. Emitting here
|
||||
// would pair the post-edit text with a pre-edit revision counter, so let
|
||||
// the change event that follows carry both; only pure caret moves emit.
|
||||
guard self.textView.serializedText() == value else {
|
||||
return
|
||||
}
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
@@ -500,6 +507,41 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
return true
|
||||
}
|
||||
|
||||
public func textDroppableView(
|
||||
_ textDroppableView: UIView & UITextDroppable,
|
||||
proposalForDrop drop: UITextDropRequest
|
||||
) -> UITextDropProposal {
|
||||
guard droppedImageProviders(in: drop) != nil else {
|
||||
return drop.suggestedProposal
|
||||
}
|
||||
|
||||
// The composer owns image drops so UIKit does not insert NSTextAttachments
|
||||
// that the controlled plain-text value cannot represent.
|
||||
let proposal = UITextDropProposal(operation: .copy)
|
||||
proposal.dropAction = .insert
|
||||
proposal.dropPerformer = .delegate
|
||||
return proposal
|
||||
}
|
||||
|
||||
public func textDroppableView(
|
||||
_ textDroppableView: UIView & UITextDroppable,
|
||||
willPerformDrop drop: UITextDropRequest
|
||||
) {
|
||||
guard let imageProviders = droppedImageProviders(in: drop) else {
|
||||
return
|
||||
}
|
||||
textView.loadImages(from: imageProviders)
|
||||
}
|
||||
|
||||
private func droppedImageProviders(in drop: UITextDropRequest) -> [NSItemProvider]? {
|
||||
let providers = drop.dropSession.items.map(\.itemProvider)
|
||||
guard !providers.isEmpty,
|
||||
providers.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) else {
|
||||
return nil
|
||||
}
|
||||
return providers
|
||||
}
|
||||
|
||||
public func textViewDidBeginEditing(_ textView: UITextView) {
|
||||
onComposerFocus()
|
||||
}
|
||||
@@ -738,8 +780,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
let currentValue = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange([
|
||||
"value": currentValue,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
@@ -781,10 +827,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
NSMaxRange(nextRange) <= textView.attributedText.length else {
|
||||
return
|
||||
}
|
||||
self.requestedSelection = nil
|
||||
// Programmatically assigning selectedRange resets the keyboard's
|
||||
// autocorrect and predictive-text context even when the range is
|
||||
// unchanged, so a no-op assignment must be skipped.
|
||||
guard !NSEqualRanges(nextRange, textView.selectedRange) else {
|
||||
return
|
||||
}
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
self.requestedSelection = nil
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
|
||||
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import { CopyTextButton } from "./CopyTextButton";
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -359,7 +358,7 @@ function NativeTable(props: {
|
||||
}}
|
||||
>
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownTextRuns(cell).map((run) =>
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
@@ -376,6 +375,7 @@ function NativeTable(props: {
|
||||
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
|
||||
<NativeMarkdownImage
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
|
||||
|
||||
function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -534,6 +539,7 @@ function NativeList(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, childIndex)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -551,6 +557,7 @@ function NativeList(props: {
|
||||
|
||||
export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeList
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
|
||||
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
skills={skills}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
|
||||
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
|
||||
|
||||
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return entity;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntitiesOnce(value: string): string {
|
||||
return value.replace(
|
||||
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
|
||||
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
|
||||
if (decimal) {
|
||||
return String.fromCodePoint(Number.parseInt(decimal, 10));
|
||||
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
|
||||
}
|
||||
if (hexadecimal) {
|
||||
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
|
||||
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
|
||||
}
|
||||
switch (entity.toLowerCase()) {
|
||||
case "&":
|
||||
@@ -661,6 +668,7 @@ function appendDocumentBlock(
|
||||
function containsRichBlock(node: MarkdownNode): boolean {
|
||||
if (
|
||||
node.type === "code_block" ||
|
||||
node.type === "blockquote" ||
|
||||
node.type === "table" ||
|
||||
node.type === "image" ||
|
||||
node.type === "horizontal_rule" ||
|
||||
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
private val iconView = HeaderIconView(context)
|
||||
private val onTriggered by EventDispatcher()
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
onTriggered(emptyMap<String, Any>())
|
||||
}
|
||||
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
fun setLabel(label: String) {
|
||||
contentDescription = label
|
||||
}
|
||||
|
||||
fun setSystemImage(systemImage: String) {
|
||||
iconView.systemImage = systemImage
|
||||
}
|
||||
}
|
||||
|
||||
private class HeaderIconView(context: Context) : View(context) {
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.parseColor("#6B7280")
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeWidth = 3f * resources.displayMetrics.density
|
||||
style = Paint.Style.STROKE
|
||||
}
|
||||
|
||||
var systemImage: String = "gearshape"
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val size = minOf(width, height).toFloat()
|
||||
if (systemImage == "square.and.pencil") {
|
||||
drawNewTask(canvas, cx, cy, size)
|
||||
} else {
|
||||
drawSettings(canvas, cx, cy, size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val radius = size * 0.12f
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
for (index in 0 until 8) {
|
||||
val angle = Math.PI * index / 4.0
|
||||
val inner = size * 0.19f
|
||||
val outer = size * 0.27f
|
||||
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
|
||||
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
|
||||
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
|
||||
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
|
||||
canvas.drawLine(sx, sy, ex, ey, paint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val left = cx - size * 0.2f
|
||||
val top = cy - size * 0.16f
|
||||
val right = cx + size * 0.14f
|
||||
val bottom = cy + size * 0.2f
|
||||
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
|
||||
canvas.drawLine(
|
||||
cx - size * 0.02f,
|
||||
cy + size * 0.13f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
canvas.drawLine(
|
||||
cx + size * 0.17f,
|
||||
cy - size * 0.2f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user