Compare commits
273
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159021e95e | ||
|
|
4b35ac856d | ||
|
|
efb25b1596 | ||
|
|
f6022f33d0 | ||
|
|
7d233d93ad | ||
|
|
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 |
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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -84,8 +84,29 @@ jobs:
|
||||
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
|
||||
|
||||
|
||||
@@ -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,21 @@ 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)
|
||||
@@ -98,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 }}
|
||||
@@ -117,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"}`,
|
||||
);
|
||||
@@ -52,6 +52,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
@@ -100,6 +101,7 @@ jobs:
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=t3...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
|
||||
@@ -746,16 +746,10 @@ 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:
|
||||
@@ -823,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 }}
|
||||
@@ -840,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 }}
|
||||
@@ -860,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
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
- `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.
|
||||
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
|
||||
- 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.
|
||||
- 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
|
||||
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- 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.
|
||||
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
|
||||
- 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.
|
||||
|
||||
@@ -68,6 +68,7 @@ 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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.31",
|
||||
"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,12 +18,15 @@ 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";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
@@ -220,20 +224,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 +278,17 @@ 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* DesktopRemoteUpdates.listen;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -66,6 +67,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,8 +150,11 @@ 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 branding = resolveDesktopAppBranding({
|
||||
@@ -156,12 +162,18 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
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({
|
||||
@@ -205,6 +217,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),
|
||||
|
||||
@@ -35,6 +35,7 @@ describe("DesktopLifecycle", () => {
|
||||
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);
|
||||
@@ -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");
|
||||
}
|
||||
@@ -165,6 +165,8 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,6 +72,8 @@ function makePoolLayer(
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
@@ -91,6 +93,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"]),
|
||||
),
|
||||
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
removeSwitchMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -34,6 +35,7 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
removeSwitchMock: vi.fn(),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -52,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
removeSwitch: removeSwitchMock,
|
||||
},
|
||||
dock: {
|
||||
setIcon: setDockIconMock,
|
||||
@@ -89,6 +92,7 @@ describe("ElectronApp", () => {
|
||||
quitMock.mockClear();
|
||||
relaunchMock.mockClear();
|
||||
removeListenerMock.mockClear();
|
||||
removeSwitchMock.mockClear();
|
||||
setPathMock.mockClear();
|
||||
});
|
||||
|
||||
@@ -178,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)),
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -43,12 +43,14 @@ 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";
|
||||
@@ -181,6 +183,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
@@ -195,16 +198,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>()(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -109,7 +110,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",
|
||||
@@ -406,6 +407,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") {
|
||||
@@ -1365,6 +1373,15 @@ 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(
|
||||
@@ -1792,7 +1809,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 }, () => {
|
||||
@@ -1807,14 +1824,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* () {
|
||||
@@ -1844,11 +1861,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(
|
||||
@@ -3586,7 +3605,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"),
|
||||
);
|
||||
|
||||
@@ -43,6 +43,7 @@ function makeElectronAppLayer(
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
@@ -155,8 +156,11 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const hello = messages[0];
|
||||
if (hello?.type !== "desktopTelemetryHello") {
|
||||
return assert.fail("Expected the first telemetry message to be the hello.");
|
||||
}
|
||||
assert.equal(hello.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
@@ -384,4 +388,80 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes requestDesktopUpdate control messages and replays update reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Effect.succeed(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)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
const requestFiber = yield* Stream.runHead(publisher.updateRequests).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("test", {
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId: "req-9",
|
||||
});
|
||||
const received = yield* Fiber.join(requestFiber);
|
||||
assert.equal(Option.getOrThrow(received).requestId, "req-9");
|
||||
|
||||
const report = {
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
outcome: "up-to-date",
|
||||
state: {
|
||||
enabled: true,
|
||||
status: "up-to-date",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
},
|
||||
} as const;
|
||||
yield* publisher.publishUpdateReport(report);
|
||||
|
||||
// A subscriber that attaches after the publish (the backend spawned
|
||||
// by a relaunch) still sees the latest report replayed.
|
||||
const decoder = new TextDecoder();
|
||||
const decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const replayed = yield* publisher.encoded.pipe(
|
||||
Stream.mapEffect((bytes) => decodeMessage(decoder.decode(bytes).trim())),
|
||||
Stream.filter((message) => message.type === "desktopUpdateStatus"),
|
||||
Stream.runHead,
|
||||
);
|
||||
const replayedReport = Option.getOrThrow(replayed);
|
||||
if (replayedReport.type !== "desktopUpdateStatus") {
|
||||
return assert.fail("Expected a desktop update status report.");
|
||||
}
|
||||
assert.equal(replayedReport.outcome, "up-to-date");
|
||||
assert.equal(replayedReport.state.currentVersion, "1.2.3");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryRequestDesktopUpdate,
|
||||
type DesktopUpdateStatusReport,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -65,6 +67,12 @@ export class DesktopTelemetryPublisher extends Context.Service<
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
/** Sends the report to the attached backend and replays the latest one
|
||||
to backends that attach later (including the one spawned after a
|
||||
relaunch). */
|
||||
readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
|
||||
/** Update requests received over the control channel. Single consumer. */
|
||||
readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
@@ -160,6 +168,9 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
|
||||
const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
|
||||
const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
@@ -324,6 +335,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
case "requestDesktopUpdate":
|
||||
return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
@@ -357,15 +370,36 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
);
|
||||
}),
|
||||
);
|
||||
const updateReports = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(updateReportChanges);
|
||||
const initial = yield* Ref.get(latestUpdateReport);
|
||||
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,
|
||||
Stream.merge(snapshots, updateReports),
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
|
||||
report,
|
||||
) =>
|
||||
Ref.set(latestUpdateReport, Option.some(report)).pipe(
|
||||
Effect.andThen(PubSub.publish(updateReportChanges, report)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
@@ -373,6 +407,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
handleControl,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
publishUpdateReport,
|
||||
updateRequests: Stream.fromQueue(updateRequestQueue),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateStatusReport,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import { makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
// The remote flow hops between the test runtime's fibers and the updater's
|
||||
// runPromise-driven event handlers, so settling needs real microtask turns,
|
||||
// not just fiber yields.
|
||||
const settle = Effect.gen(function* () {
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
});
|
||||
|
||||
const request = (requestId: string): DesktopTelemetryRequestDesktopUpdate => ({
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId,
|
||||
});
|
||||
|
||||
function runRemoteUpdatesTest(
|
||||
harness: ReturnType<typeof makeHarness>,
|
||||
body: (context: {
|
||||
readonly reports: DesktopUpdateStatusReport[];
|
||||
readonly requests: Queue.Queue<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}) => Effect.Effect<void, never, DesktopUpdates.DesktopUpdates>,
|
||||
) {
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requests = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
const reports: DesktopUpdateStatusReport[] = [];
|
||||
const publisher = DesktopTelemetryPublisher.DesktopTelemetryPublisher.of({
|
||||
latest: Effect.succeedNone,
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: (report) =>
|
||||
Effect.sync(() => {
|
||||
reports.push(report);
|
||||
}),
|
||||
updateRequests: Stream.fromQueue(requests),
|
||||
});
|
||||
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen.pipe(
|
||||
Effect.provideService(DesktopTelemetryPublisher.DesktopTelemetryPublisher, publisher),
|
||||
);
|
||||
yield* settle;
|
||||
yield* body({ reports, requests });
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}
|
||||
|
||||
function terminalReports(reports: DesktopUpdateStatusReport[]): DesktopUpdateStatusReport[] {
|
||||
return reports.filter((report) => report.outcome !== undefined);
|
||||
}
|
||||
|
||||
describe("DesktopRemoteUpdates", () => {
|
||||
it.effect("drives check, download, and install with no local confirmation", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-1"));
|
||||
yield* settle;
|
||||
assert.equal(harness.checkCount(), 1);
|
||||
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "installing");
|
||||
assert.equal(terminals[0]?.requestId, "req-1");
|
||||
assert.equal(harness.quitAndInstalls(), 1);
|
||||
|
||||
// The mirror stamped the in-run state changes with the request id.
|
||||
const statuses = reports
|
||||
.filter((report) => report.requestId === "req-1")
|
||||
.map((report) => report.state.status);
|
||||
assert.include(statuses, "available");
|
||||
assert.include(statuses, "downloaded");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports a failed outcome when quitAndInstall fails", () => {
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("spawn failed"),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-4"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
// Install failures reduce to status "downloaded" + errorContext
|
||||
// "install"; the run must still end with a failed report after the
|
||||
// premature "installing" one.
|
||||
const terminals = terminalReports(reports);
|
||||
assert.deepEqual(
|
||||
terminals.map((report) => report.outcome),
|
||||
["installing", "failed"],
|
||||
);
|
||||
assert.equal(terminals[1]?.state.errorContext, "install");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not misread a lingering install error as a failed retry", () => {
|
||||
let installAttempts = 0;
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.suspend(() => {
|
||||
installAttempts += 1;
|
||||
return installAttempts === 1
|
||||
? Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("first attempt failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-5"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
// First run failed; state is "downloaded" with a lingering
|
||||
// errorContext "install". The retry succeeds and must not report
|
||||
// that leftover as a fresh failure.
|
||||
yield* Queue.offer(requests, request("req-6"));
|
||||
yield* settle;
|
||||
|
||||
const retryTerminals = terminalReports(reports).filter(
|
||||
(report) => report.requestId === "req-6",
|
||||
);
|
||||
assert.deepEqual(
|
||||
retryTerminals.map((report) => report.outcome),
|
||||
["installing"],
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports up-to-date without installing when there is no update", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-2"));
|
||||
yield* settle;
|
||||
harness.emit("update-not-available");
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "up-to-date");
|
||||
assert.equal(terminals[0]?.requestId, "req-2");
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails fast with the disabled reason when updates are off", () => {
|
||||
const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-3"));
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "failed");
|
||||
assert.equal(
|
||||
terminals[0]?.reason,
|
||||
"Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.",
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateRemoteOutcome,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import {
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
|
||||
|
||||
/**
|
||||
* Server-triggered desktop updates. Forks two fibers into the surrounding
|
||||
* scope: one mirrors every updater state change to the attached backend (so
|
||||
* the server always knows the desktop's update state), one consumes
|
||||
* requestDesktopUpdate control messages and drives check -> download ->
|
||||
* quit-and-install with no local confirmation. The remote click that caused
|
||||
* the request is the consent.
|
||||
*/
|
||||
export const listen: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const activeRequestIdRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const publishReport = (
|
||||
state: DesktopUpdateState,
|
||||
terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
|
||||
): Effect.Effect<void> =>
|
||||
Ref.get(activeRequestIdRef).pipe(
|
||||
Effect.flatMap((requestId) =>
|
||||
publisher.publishUpdateReport({
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
...(Option.isSome(requestId) ? { requestId: requestId.value } : {}),
|
||||
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
|
||||
...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
|
||||
state,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
yield* publishReport(latest);
|
||||
yield* Stream.runForEach(changes, (state) => publishReport(state));
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
|
||||
yield* logInfo("remote update requested", { requestId: request.requestId });
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
const disabledReason = Option.getOrNull(yield* updates.disabledReason);
|
||||
let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
// Returns true when the run reached a terminal outcome.
|
||||
const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
|
||||
switch (next.action) {
|
||||
case "wait":
|
||||
return false;
|
||||
case "check":
|
||||
attempts = { ...attempts, checks: attempts.checks + 1 };
|
||||
yield* Effect.forkScoped(updates.check("remote-update"));
|
||||
return false;
|
||||
case "download":
|
||||
attempts = { ...attempts, downloads: attempts.downloads + 1 };
|
||||
yield* Effect.forkScoped(updates.download);
|
||||
return false;
|
||||
case "install": {
|
||||
// The terminal report must go out BEFORE installing:
|
||||
// install stops the backend server first, so anything
|
||||
// published after this point never reaches the requester.
|
||||
yield* publishReport(state, { outcome: "installing" });
|
||||
yield* logInfo("remote update installing", { requestId: request.requestId });
|
||||
const before = yield* updates.getState;
|
||||
const result = yield* updates.install;
|
||||
if (!result.accepted) {
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: "The desktop app could not start the install.",
|
||||
});
|
||||
} else if (result.state !== before) {
|
||||
// During an accepted install the only state writes are the
|
||||
// failure reducers, so a transition means this attempt
|
||||
// failed. Field checks cannot tell a fresh failure from a
|
||||
// lingering errorContext left by a previous attempt, which
|
||||
// success does not clear.
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: result.state.message ?? "The desktop app failed to install the update.",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "done":
|
||||
yield* publishReport(state, {
|
||||
outcome: next.outcome,
|
||||
...(next.reason === undefined ? {} : { reason: next.reason }),
|
||||
});
|
||||
yield* logInfo("remote update finished", {
|
||||
requestId: request.requestId,
|
||||
outcome: next.outcome,
|
||||
reason: next.reason ?? null,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (yield* step(latest)) return;
|
||||
yield* changes.pipe(
|
||||
Stream.mapEffect(step),
|
||||
Stream.takeUntil((done) => done),
|
||||
Stream.runDrain,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(Ref.set(activeRequestIdRef, Option.none())),
|
||||
Effect.catchCause((cause) =>
|
||||
logError("remote update request failed unexpectedly", {
|
||||
requestId: request.requestId,
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Sequential by construction: a second remote request queued mid-run is
|
||||
// handled after the current one, when the state machine resolves it fast.
|
||||
yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
|
||||
});
|
||||
@@ -1,6 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,201 +9,14 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
@@ -274,6 +85,29 @@ describe("DesktopUpdates", () => {
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("subscribe delivers the latest state plus subsequent changes", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
assert.equal(latest.status, "idle");
|
||||
|
||||
const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild);
|
||||
yield* flushCallbacks;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const observed = yield* Fiber.join(nextState);
|
||||
assert.equal(Option.getOrThrow(observed).status, "available");
|
||||
assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("updates and broadcasts state from updater events", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
|
||||
@@ -14,9 +14,12 @@ 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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -150,6 +153,15 @@ export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
/** Current state plus a stream of every later state change. */
|
||||
readonly subscribe: Effect.Effect<
|
||||
{
|
||||
readonly latest: DesktopUpdateState;
|
||||
readonly changes: Stream.Stream<DesktopUpdateState>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
@@ -268,12 +280,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
|
||||
// Makes ref writes + publishes atomic against subscribe, so a snapshot
|
||||
// never overlaps with the first change a subscriber receives.
|
||||
const stateMutex = yield* Semaphore.make(1);
|
||||
|
||||
const emitState = Ref.get(updateStateRef).pipe(
|
||||
Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
|
||||
);
|
||||
|
||||
const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
|
||||
stateMutex
|
||||
.withPermits(1)(
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
|
||||
)
|
||||
.pipe(Effect.andThen(emitState));
|
||||
|
||||
const updateState = (
|
||||
f: (state: DesktopUpdateState) => DesktopUpdateState,
|
||||
@@ -705,6 +726,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return DesktopUpdates.of({
|
||||
getState: Ref.get(updateStateRef),
|
||||
subscribe: stateMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(stateChanges);
|
||||
const latest = yield* Ref.get(updateStateRef);
|
||||
return { latest, changes: Stream.fromSubscription(subscription) };
|
||||
}),
|
||||
),
|
||||
emitState,
|
||||
disabledReason: resolveDisabledReason,
|
||||
configure: Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
MAX_REMOTE_UPDATE_CHECKS,
|
||||
MAX_REMOTE_UPDATE_DOWNLOADS,
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const NO_ATTEMPTS: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("nextRemoteDesktopUpdateStep", () => {
|
||||
it("fails immediately when updates are disabled, preferring the known reason", () => {
|
||||
const state = makeState({ enabled: false, status: "disabled" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, "dev build"), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "dev build",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "Automatic updates are disabled on this machine.",
|
||||
});
|
||||
});
|
||||
|
||||
it("installs only from the downloaded status the updater will accept", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloaded", downloadedVersion: "1.2.4" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A previous install failure keeps status "downloaded", so a remote run
|
||||
// retries the install.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.2.4",
|
||||
errorContext: "install",
|
||||
message: "quitAndInstall failed",
|
||||
}),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A leftover downloadedVersion on an error state (background updater
|
||||
// error) must not report an install the updater refuses: fresh runs
|
||||
// re-check, and post-check it fails.
|
||||
const staleError = makeState({
|
||||
status: "error",
|
||||
downloadedVersion: "1.2.4",
|
||||
message: "background updater error",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, { checks: 1, downloads: 0 }, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "background updater error",
|
||||
});
|
||||
});
|
||||
|
||||
it("rides along while a check or download is already in flight", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "checking" }), NO_ATTEMPTS, null),
|
||||
{
|
||||
action: "wait",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloading", availableVersion: "1.2.4", downloadPercent: 40 }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "wait" },
|
||||
);
|
||||
});
|
||||
|
||||
it("downloads an available update until the attempt cap, then fails", () => {
|
||||
const available = makeState({ status: "available", availableVersion: "1.2.4" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(available, NO_ATTEMPTS, null), {
|
||||
action: "download",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
available,
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app failed to download the update.",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "available",
|
||||
availableVersion: "1.2.4",
|
||||
message: "network blipped",
|
||||
}),
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "network blipped" },
|
||||
);
|
||||
});
|
||||
|
||||
it("re-checks stale up-to-date and error states before trusting them", () => {
|
||||
// These states are retained from earlier/background checks; a remote
|
||||
// request must look again instead of replaying them.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), NO_ATTEMPTS, null),
|
||||
{ action: "check" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "check" },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports up-to-date and error states as terminal after this run's check", () => {
|
||||
const checked = { checks: 1, downloads: 0 };
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), checked, null),
|
||||
{ action: "done", outcome: "up-to-date" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
checked,
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "feed unreachable" },
|
||||
);
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState({ status: "error" }), checked, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app update failed.",
|
||||
});
|
||||
});
|
||||
|
||||
it("checks from idle until the attempt cap, then fails", () => {
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState(), NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState(),
|
||||
{ checks: MAX_REMOTE_UPDATE_CHECKS, downloads: 0 },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { DesktopUpdateRemoteOutcome, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* What a server-triggered update run should do next, given the updater's
|
||||
* current state. "wait" means an action (possibly started locally) is in
|
||||
* flight and the run should ride along until the next state change.
|
||||
*/
|
||||
export type RemoteDesktopUpdateStep =
|
||||
| { readonly action: "check" }
|
||||
| { readonly action: "download" }
|
||||
| { readonly action: "install" }
|
||||
| { readonly action: "wait" }
|
||||
| {
|
||||
readonly action: "done";
|
||||
readonly outcome: DesktopUpdateRemoteOutcome;
|
||||
readonly reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many times this run already issued each action. The caps are what stop
|
||||
* a check -> up-to-date -> check loop and endless download retries; they are
|
||||
* counts rather than booleans because a state event raced by the local
|
||||
* 4-minute poller can re-show an already-handled status once.
|
||||
*/
|
||||
export interface RemoteDesktopUpdateAttempts {
|
||||
readonly checks: number;
|
||||
readonly downloads: number;
|
||||
}
|
||||
|
||||
export const MAX_REMOTE_UPDATE_CHECKS = 2;
|
||||
export const MAX_REMOTE_UPDATE_DOWNLOADS = 3;
|
||||
|
||||
export function nextRemoteDesktopUpdateStep(
|
||||
state: DesktopUpdateState,
|
||||
attempts: RemoteDesktopUpdateAttempts,
|
||||
disabledReason: string | null,
|
||||
): RemoteDesktopUpdateStep {
|
||||
if (!state.enabled || state.status === "disabled") {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: disabledReason ?? "Automatic updates are disabled on this machine.",
|
||||
};
|
||||
}
|
||||
// Only "downloaded" is installable: installDownloadedUpdate rejects any
|
||||
// other status. A leftover downloadedVersion on an "error" state (e.g. a
|
||||
// background updater error) must fall through to the error branch instead
|
||||
// of reporting an install that the updater will refuse.
|
||||
if (state.status === "downloaded") {
|
||||
return { action: "install" };
|
||||
}
|
||||
if (state.status === "downloading" || state.status === "checking") {
|
||||
return { action: "wait" };
|
||||
}
|
||||
if (state.status === "available") {
|
||||
if (attempts.downloads >= MAX_REMOTE_UPDATE_DOWNLOADS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app failed to download the update.",
|
||||
};
|
||||
}
|
||||
return { action: "download" };
|
||||
}
|
||||
// "up-to-date" and "error" are retained from earlier/background checks,
|
||||
// so before this run has issued its own check they are stale, not
|
||||
// terminal: the whole point of a remote request is to look again.
|
||||
if (state.status === "up-to-date") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return { action: "done", outcome: "up-to-date" };
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app update failed.",
|
||||
};
|
||||
}
|
||||
// status === "idle"
|
||||
if (attempts.checks >= MAX_REMOTE_UPDATE_CHECKS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
};
|
||||
}
|
||||
return { action: "check" };
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
|
||||
electron-updater events are driven by hand via `emit`. Used by
|
||||
DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
|
||||
|
||||
export const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
export interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
export function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let quitAndInstallCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () =>
|
||||
Effect.sync(() => {
|
||||
quitAndInstallCount += 1;
|
||||
}).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
quitAndInstalls: () => quitAndInstallCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -46,18 +46,20 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
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"]);
|
||||
|
||||
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
subscribe: Effect.die("unexpected subscribe"),
|
||||
emitState: Effect.void,
|
||||
disabledReason: Effect.succeed(Option.none()),
|
||||
configure: Effect.void,
|
||||
@@ -79,6 +81,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 +96,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 +127,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 +146,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) =>
|
||||
|
||||
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
</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>
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.1",
|
||||
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: {
|
||||
@@ -320,6 +338,7 @@ const config: ExpoConfig = {
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
"./plugins/withAndroidTabletOrientation.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
-11
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
import UIKit
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
@@ -32,6 +33,50 @@ public final class T3NativeControlsModule: Module {
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseOrientation") { () -> String? in
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseOrientation"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
// Rotates the interface without Simulator menu UI scripting, which CI
|
||||
// runners cannot perform (osascript is denied Accessibility access there).
|
||||
AsyncFunction("applyShowcaseOrientation") { (orientation: String) in
|
||||
guard #available(iOS 16.0, *) else { return }
|
||||
let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
|
||||
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
|
||||
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
|
||||
NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
|
||||
}
|
||||
for window in windowScene.windows {
|
||||
window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
|
||||
}
|
||||
}
|
||||
}.runOnQueue(.main)
|
||||
|
||||
// The geometry request above can fail transiently (for example before the
|
||||
// scene is foreground-active), so callers poll this until it settles.
|
||||
// Screen bounds — not the scene's interface orientation — decide the
|
||||
// answer because they match the captured framebuffer: with iPadOS
|
||||
// windowing active, a floating landscape window still reports a portrait
|
||||
// screen, and screenshots would come out portrait.
|
||||
AsyncFunction("getInterfaceOrientation") { () -> String in
|
||||
guard
|
||||
let windowScene = UIApplication.shared.connectedScenes
|
||||
.compactMap({ $0 as? UIWindowScene })
|
||||
.first
|
||||
else {
|
||||
return "unknown"
|
||||
}
|
||||
let bounds = windowScene.screen.coordinateSpace.bounds
|
||||
return bounds.width > bounds.height ? "landscape" : "portrait"
|
||||
}.runOnQueue(.main)
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
@@ -42,16 +87,5 @@ public final class T3NativeControlsModule: Module {
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ fails, run `xcodebuild -downloadComponent MetalToolchain`.
|
||||
## Rebuilding libghostty-vt for Android
|
||||
|
||||
The checked-in Android shared libraries and headers are pinned to the revision recorded in
|
||||
`Vendor/libghostty-vt/VERSION`. Set `ANDROID_NDK_HOME` and run:
|
||||
`native/libghostty-vt/VERSION` at the repository root. Set `ANDROID_NDK_HOME` and run:
|
||||
|
||||
```bash
|
||||
apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh
|
||||
|
||||
@@ -18,13 +18,14 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
|
||||
## Ghostty / libghostty-vt
|
||||
|
||||
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
|
||||
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
|
||||
|
||||
- Upstream project: https://github.com/ghostty-org/ghostty
|
||||
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
|
||||
- License: MIT
|
||||
|
||||
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
|
||||
updating `Vendor/libghostty-vt`.
|
||||
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
|
||||
artifacts in sync when updating the repository-root `native/libghostty-vt`.
|
||||
|
||||
## MesloLGS NF (Android terminal font)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ add_library(t3terminal SHARED t3_terminal_jni.cpp)
|
||||
|
||||
target_include_directories(
|
||||
t3terminal
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Vendor/libghostty-vt/include"
|
||||
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../../native/libghostty-vt/include"
|
||||
)
|
||||
|
||||
target_link_options(
|
||||
|
||||
@@ -535,6 +535,12 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.isEmpty {
|
||||
feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
|
||||
lastAppliedBuffer = ""
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.hasPrefix(lastAppliedBuffer) {
|
||||
let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
|
||||
feedData(Data(suffix.utf8))
|
||||
|
||||
@@ -4,7 +4,7 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MODULE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
VENDOR_DIR="${MODULE_DIR}/Vendor/libghostty-vt"
|
||||
VENDOR_DIR="${MODULE_DIR}/../../../../native/libghostty-vt"
|
||||
PATCH_DIR="${SCRIPT_DIR}/libghostty-android-patches"
|
||||
|
||||
GHOSTTY_REVISION="${GHOSTTY_REVISION:-9f62873bf195e4d8a762d768a1405a5f2f7b1697}"
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -138,5 +138,10 @@
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
},
|
||||
"reanimated": {
|
||||
"staticFeatureFlags": {
|
||||
"DISABLE_COMMIT_PAUSING_MECHANISM": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
// The top-level `orientation: "portrait"` writes android:screenOrientation="portrait"
|
||||
// into the manifest, which locks every Android device — including tablets — to
|
||||
// portrait. iOS doesn't have this problem: iPads must support all orientations
|
||||
// because the app is multitasking-capable, so only iPhones end up portrait-only.
|
||||
// Mirror that split on Android: keep the manifest lock for phones and lift it at
|
||||
// runtime on tablets (smallest width >= 600dp, the standard tablet breakpoint),
|
||||
// since requestedOrientation set at runtime overrides the manifest value.
|
||||
// FULL_USER allows all four orientations while still respecting the user's
|
||||
// auto-rotate lock, matching iPad behavior. Foldables change
|
||||
// smallestScreenWidthDp on fold/unfold without recreating the activity
|
||||
// (smallestScreenSize is in the manifest's configChanges), so the policy is
|
||||
// re-evaluated in onConfigurationChanged: unfolding past the tablet breakpoint
|
||||
// unlocks rotation, and folding back restores the portrait lock.
|
||||
|
||||
const ORIENTATION_METHODS = `
|
||||
// Applied in onCreate and re-applied on fold/unfold; added by
|
||||
// withAndroidTabletOrientation.
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
applyTabletOrientation()
|
||||
}
|
||||
|
||||
private fun applyTabletOrientation() {
|
||||
requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
|
||||
ActivityInfo.SCREEN_ORIENTATION_FULL_USER
|
||||
} else {
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const ORIENTATION_ON_CREATE_CALL = `
|
||||
applyTabletOrientation()`;
|
||||
|
||||
function insertAfter(contents, anchor, insertion, description) {
|
||||
const index = contents.indexOf(anchor);
|
||||
if (index === -1) {
|
||||
throw new Error(
|
||||
`withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
|
||||
);
|
||||
}
|
||||
const end = index + anchor.length;
|
||||
return contents.slice(0, end) + insertion + contents.slice(end);
|
||||
}
|
||||
|
||||
module.exports = function withAndroidTabletOrientation(config) {
|
||||
return withMainActivity(config, (nextConfig) => {
|
||||
let contents = nextConfig.modResults.contents;
|
||||
if (nextConfig.modResults.language !== "kt") {
|
||||
throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
|
||||
}
|
||||
if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"import android.os.Bundle",
|
||||
"\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
|
||||
"the android.os.Bundle import",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"class MainActivity : ReactActivity() {",
|
||||
ORIENTATION_METHODS,
|
||||
"the MainActivity class declaration",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"super.onCreate(null)",
|
||||
ORIENTATION_ON_CREATE_CALL,
|
||||
"the super.onCreate call",
|
||||
);
|
||||
|
||||
nextConfig.modResults.contents = contents;
|
||||
return nextConfig;
|
||||
});
|
||||
};
|
||||
+133
-42
@@ -11,14 +11,13 @@ import {
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
@@ -40,6 +39,15 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
|
||||
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
|
||||
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
|
||||
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
|
||||
import {
|
||||
NewTaskBranchPickerRouteScreen,
|
||||
NewTaskEnvironmentPickerRouteScreen,
|
||||
} from "./features/threads/NewTaskContextPickerScreens";
|
||||
import {
|
||||
ExistingThreadSettingsRouteProvider,
|
||||
ExistingThreadSettingsRouteScreen,
|
||||
NewTaskThreadSettingsRouteScreen,
|
||||
} from "./features/threads/ThreadSettingsSheet";
|
||||
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
|
||||
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
|
||||
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
|
||||
@@ -47,6 +55,8 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
@@ -61,17 +71,15 @@ import {
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import {
|
||||
FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
NATIVE_SHEET_SURFACE_COLOR,
|
||||
NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
} from "./native/sheet-surface";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
|
||||
// background stay STATIC config while still adapting to appearance changes.
|
||||
const SHEET_BACKGROUND_COLOR =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
|
||||
: undefined;
|
||||
|
||||
type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
readonly unstable_navigationItemStyle?: "editor";
|
||||
};
|
||||
@@ -90,8 +98,8 @@ const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShown: true,
|
||||
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? { backgroundColor: "transparent" }
|
||||
: SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? { backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
|
||||
@@ -108,10 +116,10 @@ const SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
NATIVE_SHEET_SURFACE_COLOR !== undefined
|
||||
? // native-stack types this as `string`, but the native side accepts any
|
||||
// ColorValue including DynamicColorIOS.
|
||||
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
{ backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: false,
|
||||
@@ -124,6 +132,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
// A native glass header for a sheet screen whose primary child is a scroll
|
||||
// view. The centered sheet title stays stable while UIKit supplies scroll-edge
|
||||
// fading from that child.
|
||||
const SHEET_GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
headerBackVisible: false,
|
||||
@@ -132,7 +148,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
const SettingsContentStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
@@ -175,6 +191,13 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Appearance",
|
||||
},
|
||||
}),
|
||||
SettingsProjectGrouping: createNativeStackScreen({
|
||||
screen: SettingsProjectGroupingRouteScreen,
|
||||
linking: "project-grouping",
|
||||
options: {
|
||||
title: "Project Grouping",
|
||||
},
|
||||
}),
|
||||
SettingsClientStorage: createNativeStackScreen({
|
||||
screen: SettingsClientStorageRouteScreen,
|
||||
linking: "client-storage",
|
||||
@@ -182,20 +205,37 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Client Storage",
|
||||
},
|
||||
}),
|
||||
SettingsUsage: createNativeStackScreen({
|
||||
screen: UsageRouteScreen,
|
||||
linking: "usage",
|
||||
options: {
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// The outer stack never owns visible chrome. Settings routes render inside a
|
||||
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
|
||||
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "SettingsContent",
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
SettingsContent: createNativeStackScreen({
|
||||
screen: SettingsContentStack,
|
||||
linking: "",
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -213,9 +253,16 @@ const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
|
||||
const NewTaskSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "NewTask",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
...SHEET_GLASS_HEADER_OPTIONS,
|
||||
// The form-sheet host owns the one opaque adaptive surface. Child screens
|
||||
// and the navigation bar stay transparent over it, avoiding visible color
|
||||
// slabs as view controllers move horizontally.
|
||||
contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
// UIKit's default push adds a dimming shadow and independently transitions
|
||||
// the navigation bar. Both read as mismatched sheet backgrounds here.
|
||||
// simple_push retains native push/pop gestures without either artifact.
|
||||
animation: Platform.OS === "ios" ? "simple_push" : undefined,
|
||||
animationDuration: Platform.OS === "ios" ? 350 : undefined,
|
||||
},
|
||||
screens: {
|
||||
NewTask: createNativeStackScreen({
|
||||
@@ -228,9 +275,39 @@ const NewTaskSheetStack = createNativeStackNavigator({
|
||||
NewTaskDraft: createNativeStackScreen({
|
||||
screen: NewTaskDraftRouteScreen,
|
||||
linking: "draft",
|
||||
// The draft composer has no scroll view for glass to sample; a solid
|
||||
// header also lays the content out below the bar (no manual inset).
|
||||
options: SHEET_SOLID_HEADER_OPTIONS,
|
||||
options: {
|
||||
headerBackVisible: false,
|
||||
title: "",
|
||||
},
|
||||
}),
|
||||
NewTaskEnvironment: createNativeStackScreen({
|
||||
screen: NewTaskEnvironmentPickerRouteScreen,
|
||||
linking: "draft/environment",
|
||||
options: {
|
||||
title: "Environment",
|
||||
},
|
||||
}),
|
||||
NewTaskBranch: createNativeStackScreen({
|
||||
screen: NewTaskBranchPickerRouteScreen,
|
||||
linking: "draft/branch",
|
||||
options: {
|
||||
title: "Branch",
|
||||
},
|
||||
}),
|
||||
ThreadSettings: createNativeStackScreen({
|
||||
screen: NewTaskThreadSettingsRouteScreen,
|
||||
linking: "draft/settings",
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
AddProject: createNativeStackScreen({
|
||||
screen: AddProjectSourceRoute,
|
||||
@@ -269,6 +346,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"SettingsLegal",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
"ThreadSettingsSheet",
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -331,11 +409,11 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<ExistingThreadSettingsRouteProvider>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</ExistingThreadSettingsRouteProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
@@ -417,7 +495,9 @@ export const RootStack = createNativeStackNavigator({
|
||||
options: {
|
||||
// Android cannot host the keyboard-driven comment composer inside a
|
||||
// formSheet; use a full-screen modal there instead.
|
||||
presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet",
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "fullScreenModal" as const }
|
||||
: FORM_SHEET_PRESENTATION_OPTIONS),
|
||||
sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92],
|
||||
sheetGrabberVisible: Platform.OS !== "android",
|
||||
},
|
||||
@@ -427,10 +507,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files`,
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR }
|
||||
: undefined,
|
||||
contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE,
|
||||
title: "Files",
|
||||
},
|
||||
}),
|
||||
@@ -439,11 +516,25 @@ export const RootStack = createNativeStackNavigator({
|
||||
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadSettingsSheet: createNativeStackScreen({
|
||||
screen: ExistingThreadSettingsRouteScreen,
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [1],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
GitOverview: createNativeStackScreen({
|
||||
screen: GitOverviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -452,7 +543,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitCommitSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -461,7 +552,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitBranchesSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -470,7 +561,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: GitConfirmSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.45, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -486,7 +577,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.7, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -509,7 +600,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.6, 0.95],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -524,7 +615,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const, headerShown: false }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
@@ -534,7 +625,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "connections/new",
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
@@ -554,7 +645,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...(Platform.OS === "android"
|
||||
? { presentation: "card" as const }
|
||||
: {
|
||||
presentation: "formSheet" as const,
|
||||
...FORM_SHEET_PRESENTATION_OPTIONS,
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}),
|
||||
|
||||
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={props.onBack}
|
||||
className="size-11 items-center justify-center"
|
||||
className="-mr-2 size-11 items-center justify-center"
|
||||
>
|
||||
<SymbolView
|
||||
name="chevron.left"
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
IconBellRinging,
|
||||
IconBolt,
|
||||
IconCamera,
|
||||
IconChartBar,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconCode,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
IconChevronUp,
|
||||
IconCircleCheck,
|
||||
IconCircleXFilled,
|
||||
IconClock,
|
||||
IconCopy,
|
||||
IconDeviceDesktop,
|
||||
IconDots,
|
||||
@@ -49,6 +51,8 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStopFilled,
|
||||
IconPlus,
|
||||
@@ -94,8 +98,10 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"bolt.circle": IconBolt,
|
||||
"bolt.horizontal.circle": IconBolt,
|
||||
camera: IconCamera,
|
||||
"chart.bar.xaxis": IconChartBar,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
"chevron.down": IconChevronDown,
|
||||
"chevron.left": IconChevronLeft,
|
||||
"chevron.left.forwardslash.chevron.right": IconCode,
|
||||
@@ -119,6 +125,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
play: IconPlayerPlay,
|
||||
plus: IconPlus,
|
||||
"qrcode.viewfinder": IconQrcode,
|
||||
|
||||
@@ -16,6 +16,18 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
|
||||
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
|
||||
|
||||
/**
|
||||
* Horizontal correction applied to content rendered in the brand title slot,
|
||||
* shared with the connection-status swap so both align identically.
|
||||
*/
|
||||
export function brandTitleOffset(nativeLeadingItem: boolean): number {
|
||||
if (Platform.OS !== "ios") return 0;
|
||||
if (nativeLeadingItem) {
|
||||
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
|
||||
}
|
||||
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
@@ -28,16 +40,7 @@ export function CompactBrandTitle(
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
const titleOffset =
|
||||
Platform.OS !== "ios"
|
||||
? 0
|
||||
: props.nativeLeadingItem
|
||||
? Platform.isPad
|
||||
? IPAD_NATIVE_LEADING_TITLE_OFFSET
|
||||
: IOS_NATIVE_LEADING_TITLE_OFFSET
|
||||
: Platform.isPad
|
||||
? IPAD_HOME_TITLE_OFFSET
|
||||
: 0;
|
||||
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
|
||||
|
||||
return (
|
||||
<View
|
||||
|
||||
+65
-5
@@ -17,11 +17,73 @@ import { cn } from "../lib/cn";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
|
||||
export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44;
|
||||
export const COMPOSER_TOOLBAR_GAP = 8;
|
||||
export const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_GAP = 8;
|
||||
const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
|
||||
const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;
|
||||
|
||||
/**
|
||||
* Quiet inline composer control used inside cards and their context rows.
|
||||
* Unlike ComposerToolbarButton, this does not draw another pill inside the
|
||||
* composer surface, so model and workspace controls read as part of the card.
|
||||
*/
|
||||
export function ComposerInlineControl(props: {
|
||||
readonly accessibilityHint?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly disabled?: boolean;
|
||||
readonly emphasized?: boolean;
|
||||
readonly icon?: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly iconNode?: ReactNode;
|
||||
readonly label: string;
|
||||
readonly maxWidth?: number;
|
||||
readonly onPress?: () => void;
|
||||
readonly selected?: boolean;
|
||||
readonly static?: boolean;
|
||||
readonly chevronDirection?: "down" | "right";
|
||||
readonly showChevron?: boolean;
|
||||
}) {
|
||||
const iconColor = useThemeColor(
|
||||
props.emphasized || props.selected ? "--color-icon" : "--color-icon-muted",
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityHint={props.accessibilityHint}
|
||||
accessibilityRole={props.static ? undefined : "button"}
|
||||
accessibilityState={
|
||||
props.static ? undefined : { disabled: props.disabled, selected: props.selected }
|
||||
}
|
||||
className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"
|
||||
disabled={props.disabled || props.static}
|
||||
onPress={props.onPress}
|
||||
style={{ maxWidth: props.maxWidth ?? 190, opacity: props.disabled ? 0.45 : 1 }}
|
||||
>
|
||||
{props.iconNode ? (
|
||||
<View className="size-4 shrink-0 items-center justify-center">{props.iconNode}</View>
|
||||
) : props.icon ? (
|
||||
<SymbolView name={props.icon} size={16} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-sm font-t3-medium",
|
||||
props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
{props.showChevron === false ? null : (
|
||||
<SymbolView
|
||||
name={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerToolbarRow(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly paddingBottom?: number;
|
||||
@@ -247,5 +309,3 @@ export function ComposerToolbarButton(props: {
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerToolbarTrigger = ComposerToolbarButton;
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type ComponentProps,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Platform, Pressable, useColorScheme, View } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
@@ -21,10 +22,31 @@ export function ControlPill(props: {
|
||||
readonly label?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly activateOnPressIn?: boolean;
|
||||
readonly variant?: "circle" | "pill" | "primary" | "danger";
|
||||
readonly disabled?: boolean;
|
||||
readonly className?: string;
|
||||
}) {
|
||||
const variant = props.variant ?? "circle";
|
||||
const activatedOnPressInRef = useRef(false);
|
||||
|
||||
const handlePressIn = () => {
|
||||
activatedOnPressInRef.current = true;
|
||||
props.onPress?.();
|
||||
};
|
||||
const handlePressOut = () => {
|
||||
// Pressability invokes onPressOut immediately before onPress on release.
|
||||
// Defer the reset so onPress can identify the same physical gesture.
|
||||
setTimeout(() => {
|
||||
activatedOnPressInRef.current = false;
|
||||
}, 0);
|
||||
};
|
||||
const handlePress = () => {
|
||||
if (activatedOnPressInRef.current) {
|
||||
return;
|
||||
}
|
||||
props.onPress?.();
|
||||
};
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
@@ -54,6 +76,7 @@ export function ControlPill(props: {
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
@@ -68,7 +91,9 @@ export function ControlPill(props: {
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
onPress={props.activateOnPressIn ? handlePress : props.onPress}
|
||||
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
|
||||
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
@@ -133,9 +158,25 @@ export function ControlPillMenu(
|
||||
}
|
||||
|
||||
const { className: _className, ...menuProps } = props;
|
||||
let children = menuProps.children;
|
||||
// In long-press mode the wrapped pressable still receives the touch (the
|
||||
// patched MenuView button is touch-transparent) and RN's Fabric touch
|
||||
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
|
||||
// bare onPress would fire on finger-up even after the menu opened — and
|
||||
// also on a long press released just under the menu threshold. A dispatched
|
||||
// onLongPress makes Pressability swallow the release, so holds past 350ms
|
||||
// (below the ~500ms context-menu threshold) can only open the menu, never
|
||||
// tap through.
|
||||
if (props.shouldOpenOnLongPress && isValidElement(children)) {
|
||||
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
|
||||
children = cloneElement(child, {
|
||||
onLongPress: child.props.onLongPress ?? (() => undefined),
|
||||
delayLongPress: child.props.delayLongPress ?? 350,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
|
||||
{menuProps.children}
|
||||
{children}
|
||||
</MenuView>
|
||||
);
|
||||
}
|
||||
@@ -5,16 +5,19 @@ import {
|
||||
useColorScheme,
|
||||
View,
|
||||
type ColorValue,
|
||||
type StyleProp,
|
||||
type ViewProps,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
|
||||
readonly children: ReactNode;
|
||||
readonly glassEffectStyle?: "clear" | "regular" | "none";
|
||||
readonly tintColor?: ColorValue;
|
||||
readonly chrome?: "default" | "none";
|
||||
/** Styling used only when native Liquid Glass is unavailable. */
|
||||
readonly fallbackStyle?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
export function GlassSurface({
|
||||
@@ -22,6 +25,7 @@ export function GlassSurface({
|
||||
glassEffectStyle = "regular",
|
||||
chrome = "default",
|
||||
tintColor,
|
||||
fallbackStyle,
|
||||
style,
|
||||
...props
|
||||
}: GlassSurfaceProps) {
|
||||
@@ -67,7 +71,7 @@ export function GlassSurface({
|
||||
}
|
||||
|
||||
return (
|
||||
<View {...props} style={[surfaceStyle, style]}>
|
||||
<View {...props} style={[surfaceStyle, fallbackStyle, style]}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -24,13 +24,18 @@ export function ProjectFavicon(props: {
|
||||
readonly size?: number;
|
||||
readonly projectTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly faviconPath?: string | null;
|
||||
}) {
|
||||
const size = props.size ?? 42;
|
||||
const faviconUrl = useAssetUrl(
|
||||
props.environmentId,
|
||||
props.workspaceRoot === null || props.workspaceRoot === undefined
|
||||
? null
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
: {
|
||||
_tag: "project-favicon",
|
||||
cwd: props.workspaceRoot,
|
||||
...(props.faviconPath ? { path: props.faviconPath } : {}),
|
||||
},
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
const cacheKey =
|
||||
|
||||
@@ -9,6 +9,7 @@ type ProviderIconProps = {
|
||||
export function ProviderIcon(props: ProviderIconProps) {
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const size = props.size ?? 16;
|
||||
const mono = isDarkMode ? "#e5e5e5" : "#171717";
|
||||
|
||||
if (props.provider === "claudeAgent") {
|
||||
return (
|
||||
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "grok") {
|
||||
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
|
||||
/>
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "cursor") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#EDECEC" : "#26251E"}
|
||||
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "opencode") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
|
||||
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
|
||||
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
// codex (and unknown drivers)
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#e5e5e5" : "#171717"}
|
||||
fill={mono}
|
||||
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
|
||||
/>
|
||||
</Svg>
|
||||
|
||||
@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useFocusEffect } from "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
@@ -18,7 +17,6 @@ import {
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
@@ -70,9 +68,8 @@ export function ArchivedThreadsRouteScreen() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [expand, refresh]),
|
||||
}, [refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
Loaded 100 of 962 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user